2015-06-29 127 views
1

我想連接多個文本文件。程序工作正常,但如果我不知道文件總數,那麼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(); 
      } 
     } 
    } 

} 

回答

1

你可以使用命令行參數:

public class CommandLineTest { 
    public static void main(String[] args) { 
     int howManyFiles = Integer.parseInt(args[0]); 
    } 
} 

上面的代碼給你的第一個命令行參數,並把它當作一個整數。但是,在你的代碼中,你應該檢查是否真的有一個指定的整數。

+0

好主意讓它在用戶+1 – maskacovnik

2

嘗試獲取文件的數組,在目錄:

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()

+0

我還沒弄明白。我試圖自動執行多個文件 – Unknown

+0

'listFiles()'metod爲您提供了一系列文件,所以'array.length'是文件的數量(它可能會增加+2,因爲'.'和'''dirs - 爲此您可以使用'FileFilter')@GauravDokania – maskacovnik

+0

但有一個'BufferedReader',我很困惑@JackWhiteIII – maskacovnik