BufferedReader和BufferedWriter

时间:2014-08-29 16:23:34

标签: java bufferedreader bufferedwriter

我有一个.txt文件。我想要一条线从'>'开始然后,第一个子弹符号'•'遇到的问题是'>>•'。我用:

br = new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\text.txt"));
bw = new BufferedWriter(new FileWriter("C:\\Users\\User\\Desktop\\text.txt"));

        while ((current_line = br.readLine()) != null) {
            if (current_line.length() > 1 && (current_line.charAt(0) == '>' || current_line.charAt(1) != '>'))  {
                found = true;
            }
            if ((found) && (current_line.length() > 1) && current_line.charAt(0) == '•') {
                bw.write(">>");
                found = false;
            }
        }
        br.close();
        bw.close();

但是这会产生一个.. empty .txt文件?我做错了什么?非常感谢

1 个答案:

答案 0 :(得分:1)

bw.write(line); bw.write("\r\n");在哪里?

try (br = new BufferedReader(new FileReader("C:\\Users\User\Desktop\\text.txt");
    bw = new BufferedWriter(new FileWriter("C:\\Users\\User\Desktop\\text-2.txt")) {

    String current_line;
    while ((current_line = br.readLine()) != null) {
        if (current_line.length() > 1 && (current_line.charAt(0) == '>' || current_line.charAt(1) != '>'))  {
            found = true;
        }
        if (found && current_line.startsWith("•")) {
            bw.write(">>");
            found = false;
        }
        bw.write(line);
        bw.write("\r\n"):
    }
}

不幸的是,你不能在这里写相同的文件。

还必须在Java字符串中转义反斜杠。

found命名为tackleBullet会更好。