首页 > 解决方案 > 读取和写入txt文件

问题描述

我正在开发一个java程序,其中:

程序读取两个 txt 文件(txt1 和 txt2),然后将 txt1 和 txt2 打印到 txt3,从每个 txt1 和 txt2 交替“行”。

例如:txt1 =

这是第一个

txt2= 那是两个

txt3 应该是:这是第一个是一二

我不确定我错过了什么......任何帮助将不胜感激。

代码:

package combine;

import java.io.*;
import java.util.*;
import java.nio.file.*;

public class Main{

public static void main(String[] args) throws IOException{
   String targetDir = "C:\\Parts";
   String outputFile = "C:\\Parts\\complete\\TheRavensGreenEggs.txt";

   File dir = new File(targetDir);
   File[] files = dir.listFiles(new FilenameFilter() {
     // Only import "txt" files
     @Override
     public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
});

// Reads all "txt" file lines into a List
List<String> inputFileLines = new ArrayList<>();{
for (File file : files) {
    inputFileLines.addAll(Files.readAllLines(Paths.get(file.getAbsolutePath())));
}}


// Writes the List to the console
for (String line : inputFileLines) {
    System.out.println(line);
}

// Writes the List to a single "TheRavensGreenEggs.txt" file
Files.write(Paths.get(outputFile), inputFileLines, StandardOpenOption.CREATE);
}}

标签: javawriting

解决方案


List<String>像这样使用java.nio

public static void main(String[] args) {
    // define the input paths and the output path
    Path file01Path = Paths.get("Y:\\our\\path\\to\\file_01.txt");
    Path file02Path = Paths.get("Y:\\our\\path\\to\\file_02.txt");
    Path outputPath = Paths.get("Y:\\our\\path\\to\\result.txt");
    // provide a list for the alternating lines
    List<String> resultLines = new ArrayList<>();

    try {
        // read the lines of both files and get them as lists of Strings
        List<String> linesOfFile01 = Files.readAllLines(file01Path);
        List<String> linesOfFile02 = Files.readAllLines(file02Path);
        // find a common border for the iteration: the size of the bigger list
        int maxSize = (linesOfFile01.size() >= linesOfFile02.size())
                ? linesOfFile01.size() : linesOfFile02.size();

        // then loop and store the lines (if there are any) in a certain order
        for (int i = 0; i < maxSize; i++) {
            // lines of file 01 first
            if (i < linesOfFile01.size()) {
                resultLines.add(linesOfFile01.get(i));
            }
            // lines of file 02 second
            if (i < linesOfFile02.size()) {
                resultLines.add(linesOfFile02.get(i));
            }
        }

        // after all, write the content to the result path
        Files.write(outputPath,
                resultLines,
                Charset.defaultCharset(),
                StandardOpenOption.CREATE_NEW);
    } catch (IOException e) {
        System.err.println("Some files system operation failed:");
        e.printStackTrace();
    }
}

推荐阅读