如何使用java删除替换回车和换行

时间:2016-06-27 06:47:19

标签: java carriage-return linefeed

我的目标是从证书中删除 CRLF ,并在该行的末尾附加字符串

enter image description here

我使用以下代码将其删除:

 File filename =new File("D:/text.txt");
 RandomAccessFile fw = new RandomAccessFile(filename, "rw");
            FileChannel fc = fw.getChannel();
            long oldpos;
            while (true) {
                oldpos = fc.position();
                final String lineFromFile = fw.readLine();

                if (lineFromFile.contains("-----END CERTIFICATE REQUEST-----")) {
                    System.out.println("I found "  +filename.getName());
                    fc.truncate(oldpos + lineFromFile.length());
                    fw.writeBytes(",wirte123");//appends the string to the file
                    break;
                }
            }
            fw.close();

正确添加字符串并删除 CR ,但 LF 仍然存在

enter image description here

可以请任何人帮助我。 提前致谢

1 个答案:

答案 0 :(得分:0)

由于你的行尾有2个字符,你应该删除它们。

所以你的代码应该是:

\n\r

无论如何,为了避免意外,我建议您检查并删除正确的字符:\r

\n回车 lineFromFile.replace("\\n", "").replace("\\r",""); 新行或换行

要做到这一点:

{{1}}
相关问题