如何用Java读取多个输入文件?我需要阅读多个输入(几个文本文档)并创建一个术语文档矩阵 我可以读一个这样的文件:
File file = new File("a.txt");
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream stream = null;
try
{
stream = new FileInputStream(file);
while( (ch = stream.read()) != -1)
strContent.append((char)ch);
stream.close();
}
是否有任何库可以读取多个输入文件?或者我只需要循环读取所有文件?所有文件均为txt.
答案 0 :(得分:4)
是否有任何库可以读取多个输入文件?
AFAIK,没有。
以下代码适用于将多个文件读入strContent
缓冲区。
String names = new String[]{"a.txt", "b.txt", "c.txt"};
StringBuffer strContent = new StringBuffer("");
for (String name : names) {
File file = new File(name);
int ch;
FileInputStream stream = null;
try {
stream = new FileInputStream(file);
while( (ch = stream.read()) != -1) {
strContent.append((char) ch);
}
} finally {
stream.close();
}
}
请注意,我已将close
调用移动到finally
块,以便在读取流时出现问题时不会泄漏文件描述符。主要的变化是简单地将代码放入循环中,并调整几个语句的顺序。
答案 1 :(得分:0)
您可以使用文件流类来循环读取文件,例如,您可以使用FileReader / BufferredFileReader,如下所示:
String[] fileNames = new String[]{ "fileNameWithPath1", "fileNameWithPath2"...};
for(String fileName: fileNames ) {
BufferredFileReader reader =
new BufferredFileReader(new FileReader(fileName));
System.ount.println("Start reading file : "+fileName);
String line = null;
while((line=reader.nextLine())!= null){
System.out.println(line);
}
reader.close();
System.ount.println("End reading file : "+fileName);
}
如果要读取目录中的所有文件,请使用:
File directory = new File("directoryName");
File[] filesInDir = directory.listFiles();//list all files in directory
for(File file: filesInDir) {
if(!file.isDirectory()){ //read the file if not directory
BufferredFileReader reader =
new BufferredFileReader(new FileReader(file));
System.ount.println("Start reading file : "+fileName);
String line = null;
while((line=reader.nextLine())!= null){
System.out.println(line);
}
reader.close();
System.ount.println("End reading file : "+fileName);
}
}