简体   繁体   English

如何在Java中的FileWriter中跳一个字符?

[英]how to jump a character in FileWriter in java?

Here I'm trying to write program which reads from one file and prints to other file with little modification. 在这里,我正在尝试编写一个程序,该程序可以从一个文件读取并只需少量修改即可打印到另一个文件。

I have to write to other file in such a way that I have to print new line right next from ';' 我必须以这样一种方式写入其他文件,即必须在';'的旁边打印新行。 character. 字符。 I tried the below code snippet but ended up printing newline from the ';' 我尝试了以下代码片段,但最终从';'中打印换行符 character. 字符。

Here is snippet 这是片段

try (FileReader fr = new FileReader(file); FileWriter fw = new FileWriter(file2)) {
            while ((c = fr.read()) != -1) {
                if (c == 59) {
                    fw.write("\n");
                }
                fw.write((char) c);
            }
        }

Here is the file snippet I'm trying to read 这是我要阅读的文件片段

.menu ul li{ float:left; padding:0px; margin:0px; font-size:13px;}
.menu ul li a{ display:block; float:left; background-color:#f3d987; padding:7px 12px 5px 12px; color:#000; text-decoration:none;
margin:0 4px 0 0;

You just have to write the character after the newline. 您只需要在换行符后写字符。

try (FileReader fr = new FileReader(file); FileWriter fw = new FileWriter(file2)) {
    while ((c = fr.read()) != -1) {
        fw.write((char) c);
        if (c == 59) {
            fw.write("\n");
        }
    }
}

Your problem is that you write the newline before you write the character. 您的问题是在写字符之前先写换行符。

try (FileReader fr = new FileReader(file); FileWriter fw = new FileWriter(file2)) {
    while ((c = fr.read()) != -1) {
        fw.write((char) c);
        if (c == ';') { // If last was semicolon also write a newline
            fw.write("\n");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM