首页 > 解决方案 > 文件名.println(String); 跳过每隔一行

问题描述

我必须从 .txt 文件中的实验修改测量数据。我尝试做的是一次从文件中读取一行,对其进行修改,然后将其写入一个新文件。但是,我的输出文件只包含输入中的每一行。有人可以解释我的错误吗?

import java.io.*;

public class TextMod {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\ediwi\\Desktop\\Exfys A\\Java\\Code\\DataPointsModded.txt");
        BufferedReader inFile = new BufferedReader(new FileReader("me99.txt"));
        PrintWriter outFile = new PrintWriter(new BufferedWriter(new FileWriter(file)));
        int counter = 0;

        while (true) {
            String s = inFile.readLine();
            if (counter < 11) { // I want to skip the first couple of lines
                counter++;
                continue;
            } else if (inFile.readLine() == null) {
                System.out.println(counter - 11 + "Datapoints.");
                break;
            } else outFile.println(s.replaceAll("\\t", ";"));
            counter++;
        }
        outFile.close();
    }
}

标签: javalineprintwriter

解决方案


正如 PM 77-1 在上面的评论中指出的那样,错误出现在第 21 行:

} else if (inFile.readLine() == null) {

它应该是

} else if (s == null) {


推荐阅读