ArrayList<File> vuhod = new ArrayList<>(); //Коллекция vuhod заполнена файлами File res1 = new File("D:\\allFilesContent.txt"); //Файл res1 (который точно существует) для записи того, что мы считаем из каждого файла vuhod BufferedWriter writer = new BufferedWriter(new FileWriter(res1)); for (int i = 0; i < vuhod.size(); i++) { BufferedReader reader = new BufferedReader(new FileReader(vuhod.get(i))); while (reader.ready()) { writer.write(reader.readLine()); } if (i == vuhod.size() - 1) { } else { writer.write('\r'); writer.write('\n'); } 

Why the file is not filled, and what the lines of writer.write('\r'); mean writer.write('\r'); and writer.write('\n'); ?

  • \r\n is a newline character in the Windows file system. - Peter Samokhin
  • writer.write ('\ r'); writer.write ('\ n'); then after that there will be 2 transfers in the file? - Dualist
  • one
    Not. \ r \ n is a single character and denotes a single carry. - Peter Samokhin
  • Understood, thanks) - Dualist

2 answers 2

It does not write to the file, since you do not call the flush method of the writer .

BufferedWriter writes data to its buffer (the default size of which is 8192 characters) and sends to the output stream ( FileWriter ) data from the buffer only when it is filled or when you call flush() or close() .

Also it is necessary to close the read and write streams. For this, it is convenient to use the try-with-resources construction. Calling the BufferedWriter close method, by the way, results in sending data from the buffer to the output stream, so in this case you will not have to call the flush method manually.

As a result, the code looks like this:

 List<File> vuhod = Arrays.asList(new File("in1.txt"), new File("in2.txt")); File res1 = new File("out.txt"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(res1))) { for (int i = 0; i < vuhod.size(); i++) { try (BufferedReader reader = new BufferedReader(new FileReader(vuhod.get(i)))) { while (reader.ready()) { writer.write(reader.readLine()); } if (i < vuhod.size() - 1) { writer.write('\r'); writer.write('\n'); } } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } 
  • exhaustive answer, thanks - Dualist

works for me like this:

 public static void main(String[] args) throws IOException { String path = "E:\\MyProjects\\StackO\\questions\\634328"; List<File> files = new ArrayList<>(); files.add(new File(path + "\\1.txt")) ; files.add(new File(path + "\\2.txt")) ; files.add(new File(path + "\\3.txt")) ; files.add(new File(path + "\\4.txt")) ; BufferedWriter writer = new BufferedWriter(new FileWriter(path + "\\ConcatFile.txt")); for(File file: files){ BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while ((line=reader.readLine()) != null){ writer.write(line); } reader.close(); } writer.close(); } 

This is if you really really need to clean io

  • you can and nio is simple, I'm not very good with him) - Dualist