我正在尝试连接多个文本文件。该程序运行正常,但如果我不知道文件总数,那么for
循环应如何更改?
public class MultipleMerge {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
String inFileName = "C:\\Users\\dokania\\Desktop\\Bio\\Casp10\\fasta\\out";
File file = new File("C:\\Users\\dokania\\Desktop\\New folder\\out.txt");
try {
String s;
int fileCounter = 0;
FileWriter fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
for (fileCounter = 0; fileCounter < 157; fileCounter++) {
br = new BufferedReader(new FileReader(inFileName + (fileCounter++) + ".fa"));
while ((s = br.readLine()) != null) {
bw.write(s + "\n");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
答案 0 :(得分:2)
尝试在目录中获取一个Files数组:
File[] array = new File("C:\\Users\\dokania\\Desktop\\Bio\\Casp10\\fasta\\").listFiles();
然后使用foreach循环遍历所有文件
for(File file:array){
//...
}
也许你需要使用FileFilter:
http://docs.oracle.com/javase/7/docs/api/java/io/FileFilter.html
方法listFiles()
答案 1 :(得分:1)
您可以使用命令行参数:
public class CommandLineTest {
public static void main(String[] args) {
int howManyFiles = Integer.parseInt(args[0]);
}
}
上面的代码为您提供了第一个命令行参数,并将其视为整数。在您的代码中,您应该检查是否确实存在指定的整数。