繁体   English   中英

使用Java删除换行

[英]Removing linefeeds using java

我在制表符\\t分隔文件中混合了换行符(CR / LF或\\r\\f或“ \\ n”)和换页符(LF或\\f )的文本文件。 换行符显示为预期的“ \\ n”,但换页符也用作内部字段定界符。 例:

COL_1   COL_2   COL_3    COL_4
1       A\fB    C\fD     2    

使用Java,只有在将line.separator设置为\\r (对于CR / LF或\\r\\f ,然后使用FileReader.read()检查'\\n'来读取文件后,才能删除换页符:

private void fixMe() throws Exception{

  FileReader in  = new FileReader("C:\\somefile.txt"); 
  FileReader out = new FileReader("C:\\someotherfile.txt"); 

  Syetem.setProperty("line.separator","\r");

  try {
    int c;
    while (( c = in.read()) != -1 ) {
        if ( c != '\n' ) {
             out.write(c);
        }
    }
  }
  ...

看来in.read具有一个默认设置,以两个字符的形式读取“ \\ n”。 我可以删除\\f但是现在我必须编写另一种方法来将\\r更改为“ \\ n”并重置line.separator作为该方法的一部分。 有一个更好的方法吗? 我想使用扫描仪,但是解决方法是再次重置line.separator设置,这是我要避免的。

更好的方式来读取所有文件内容,然后在需要的位置保存后删除“ \\ n和\\ r \\ n和\\ f”。

参见示例:

String content = new String(Files.readAllBytes(Paths.get("path-to-file")));
String processedContent = content.replaceAll("\\n|\\r\\n|\\f", "");

根据您的问题,似乎您想跳过文件中的换行符'\\ f'而不是CRLF \\ r \\ f,因此跟踪最后读取的字符可能会解决您的问题。

private void fixMe() throws Exception{

  FileReader in  = new FileReader("C:\\somefile.txt"); 
  FileReader out = new FileReader("C:\\someotherfile.txt"); 

//Character 10 'LF' or '\f' and 13 'CR' or '\r'
  try {
    int c;
    int prevCharRead = 0;
    while ((c = in.read()) != -1 ) {
        if(c==10 && prevCharRead!=13){
        //it's a line feed LF '\f' without the occurrence of CR '\r' before it, skip it or implement whatever logic you want.  
        }else  
           out.write(c);

        prevCharRead = c;
    }
  }
  ...

暂无
暂无

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

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