1

I am trying to concatenate multiple text files. The program is working correctly, but if I do not know the total number of files, then how should the for loop be changed?

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

}
Beau Grantham
  • 3,435
  • 5
  • 33
  • 43
Unknown
  • 25
  • 6

2 Answers2

2

Try get an array of Files in directory:

File[] array = new File("C:\\Users\\dokania\\Desktop\\Bio\\Casp10\\fasta\\").listFiles();

And then go through all files using foreach cycle

for(File file:array){
    //...
}

Maybe you'll need to use FileFilter:
http://docs.oracle.com/javase/7/docs/api/java/io/FileFilter.html
in method listFiles()

maskacovnik
  • 3,080
  • 5
  • 20
  • 26
1

You could use command line arguments:

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

Above code gives you the first command line argument and treats it as an integer. In your code, you should check if there really is an integer specified, though.

JackWhiteIII
  • 1,388
  • 2
  • 11
  • 25