-1

I have a folder with 1000 files. Each file contains text in varied number of lines. What I want and have tried to achieve is to read 'each' file and append all the lines into 1 single line (that is, I want each file to have a single line of texts).

This is what I have tried but it only prints the names of the files without effecting any changes to the files...

String line = "";
try{
    file = new FileReader(filename);
    BufferedReader reader = new BufferedReader (file);
    while ((line = reader.readLine()) != null){
        allLine.append(line);              
    }
    //System.out.println(allLine);
} catch (IOException e) {
    throw new RuntimeException("File not found");
} 
return allLine.toString();


FileWriter op = null;
op = new FileWriter(fileName);
BufferedWriter wryt = new BufferedWriter(op);
wryt.write(s);
wryt.flush();

if(op != null){
    op.close();
}


File[] lOfiles = folder.listFiles();

for (int i = 0; i< lOfiles.length; i++){
    if(lOfiles[i].isFile()){
        System.out.println(lOfiles[i].getName());
        ReadLines rd = new ReadLines();
        String rw = rd.readtxtFile(lOfiles[i].toString());
        rd.writetxtFile(lOfiles[i].getName(), rw);
    }
}
ebuka
  • 1
  • 1

1 Answers1

0
    try {
        File folder = new File("yourfolderpath");
        File out = new File("outputfile.txt");
        try(BufferedWriter bw = new BufferedWriter(new FileWriter(out))){
            for(File f: folder.listFiles()) {
                BufferedReader br = new BufferedReader(new FileReader(f));
                for(String line = br.readLine(); line!=null; line=br.readLine()) {
                    bw.write(line);
                }
            }           
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
terrywb
  • 3,740
  • 3
  • 25
  • 50
  • The problem is that the code I provided above, only reads the names/paths of the files without modifying each file by appending all the texts in each file to one single line. – ebuka Aug 27 '14 at 07:43
  • @Andrew the writeTxtFile code is the one that starts with FileWriter – ebuka Aug 27 '14 at 07:47
  • Sorry guys, I have seen my mistake. The code I posted actually did the job for me but the output was displayed in the root folder. Thanks for your comments. I do appreciate them. – ebuka Aug 27 '14 at 11:57