Подтвердить что ты не робот

Объединение нескольких .txt файлов в java

У меня есть несколько TXT файлов. Я хотел бы объединить их и создать текстовый файл. Как я могу сделать это в java?    Ниже приведен пример

        file1.txt file2.txt 

результаты конкатенации в

             file3.txt

Таким образом, соблюдается содержание file1.txt file2.txt

4b9b3361

Ответ 1

Читайте файл за файлом и записывайте их в целевой файл. Что-то вроде следующего:

    OutputStream out = new FileOutputStream(outFile);
    byte[] buf = new byte[n];
    for (String file : files) {
        InputStream in = new FileInputStream(file);
        int b = 0;
        while ( (b = in.read(buf)) >= 0)
            out.write(buf, 0, b);
        in.close();
    }
    out.close();

Ответ 2

Использование Apache Commons IO

Вы можете использовать библиотеку Apache Commons IO. Это класс FileUtils.

// Files to read
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");

// File to write
File file3 = new File("file3.txt");

// Read the file as string
String file1Str = FileUtils.readFileToString(file1);
String file2Str = FileUtils.readFileToString(file2);

// Write the file
FileUtils.write(file3, file1Str);
FileUtils.write(file3, file2Str, true); // true for append

В этом классе есть и другие методы, которые могли бы помочь выполнить задачу более оптимальным способом (например, используя потоки или списки).

Использование Java 7 +

Если вы используете Java 7 +

public static void main(String[] args) throws Exception {
    // Input files
    List<Path> inputs = Arrays.asList(
            Paths.get("file1.txt"),
            Paths.get("file2.txt")
    );

    // Output file
    Path output = Paths.get("file3.txt");

    // Charset for read and write
    Charset charset = StandardCharsets.UTF_8;

    // Join files (lines)
    for (Path path : inputs) {
        List<String> lines = Files.readAllLines(path, charset);
        Files.write(output, lines, charset, StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);
    }
}

Ответ 3

это прекрасно работает для меня.

// open file input stream to the first file file2.txt
InputStream in = new FileInputStream("file1.txt");
byte[] buffer = new byte[1 << 20];  // loads 1 MB of the file
// open file output stream to which files will be concatenated. 
OutputStream os = new FileOutputStream(new File("file3.txt"), true);
int count;
// read entire file1.txt and write it to file3.txt
while ((count = in.read(buffer)) != -1) {
    os.write(buffer, 0, count);
    os.flush();
}
in.close();
// open file input stream to the second file, file2.txt
in = new FileInputStream("file2.txt");
// read entire file2.txt and write it to file3.txt
while ((count = in.read(buffer)) != -1) {
    os.write(buffer, 0, count);
    os.flush();
}
in.close();
os.close();

Ответ 4

Вы имеете в виду, что вам нужен один файл с содержимым других текстовых файлов? Затем прочитайте каждый файл (вы можете сделать это в цикле), сохраните их содержимое в StringBuffer/ArrayList и сгенерируйте окончательный файл .txt, очистив сохраненные тексты в StringBuffer/ArrayList до финального файла .txt.

Не беспокойтесь, это непростая задача. Просто привыкнете к данной системе, тогда вы в порядке:)

Ответ 5

Звучит как домашнее задание...

  • Открыть файл 1
  • Открыть файл 2
  • Создать/открыть файл 3
  • Чтение из файла 1 и запись в файл 3
  • Закрыть файл 1
  • Чтение из файла 2 и запись в файл 3
  • Закрыть файл 2
  • Закрыть файл 3

Если вам нужно знать, как создавать/открывать/читать/записывать/закрывать файлы на Java, выполните поиск документации. Эта информация должна быть широко доступной.