Java 输出目录中多个.txt文件内的字符串
我有一个文件夹,文件名是:“名称列表”。在那个文件夹里,我有一个5.txt文件,每个文件的文件名都是一个人的名字 我想检索这五个文档并在每个文档中显示字符串。我该怎么做?我试过这个:Java 输出目录中多个.txt文件内的字符串,java,Java,我有一个文件夹,文件名是:“名称列表”。在那个文件夹里,我有一个5.txt文件,每个文件的文件名都是一个人的名字 我想检索这五个文档并在每个文档中显示字符串。我该怎么做?我试过这个: import java.io.*; import java.util.*; public class Liarliar { public static void main(String args[])throws IOException{ File Galileo = new File(
import java.io.*;
import java.util.*;
public class Liarliar {
public static void main(String args[])throws IOException{
File Galileo = new File("C:\\List of names\\Galileo.txt");
File Leonardo = new File("C:\\List of names\\Leonardo.txt");
File Rafael = new File("C:\\List of names\\Rafael.txt");
File Donatello = new File("C:\\List of names\\Donatello.txt");
File Michael = new File("C:\\List of names\\Michael.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try{
System.out.println("Enter a number list of names:");
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
}catch(FileNotFoundException e){
}catch(IOException e){
}
}
}
提前感谢某人的时间…以下几行不需要,因为它们是用来从用户那里获取输入的
System.out.println("Enter a number list of names:");
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
相反,您需要使用FileInputStream或FileReader逐个读取文件。有关如何从文件中读取数据的示例,请参见。对每个文件都这样做。不硬编码单个文件的名称(如Galileo.txt)会更通用。您可以创建一个表示目录的文件,然后调用listFiles来获取目录中的所有文件,如
File nameFile = new File(""C:\\List of names");
File[] personFiles = nameFile.listFiles();
然后您可以迭代这个文件数组,依次打开每个文件,并读取内容,如
for (File person : personFiles) {
showFileDetails(person);
}
其中,showFileDetails是您编写的用于打开文件和显示信息的单独方法