使用java删除换行符

使用java删除换行符,java,Java,我有一个文本文件,在制表符\t分隔的文件中混合使用了换行符(CR/LF或\f或“\n”)和formfeed(LF或\f)。换行符显示为预期的“\n”,但FormFeed也用作内部字段分隔符。例如: COL_1 COL_2 COL_3 COL_4 1 A\fB C\fD 2 使用Java,我只能在为CR/LF或\r\f设置line.separator到\r,然后使用FileReader.read()检查'\n'后才能删除FormFeed: priv

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

COL_1   COL_2   COL_3    COL_4
1       A\fB    C\fD     2    
使用Java,我只能在为CR/LF或
\r\f
设置
line.separator
\r
,然后使用
FileReader.read()
检查
'\n'
后才能删除FormFeed:

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);
        }
    }
  }
  ...

.read中的
似乎有一个默认设置,将“\n”读取为两个字符。我可以删除
\f
,但现在我必须编写另一个方法将
\r
更改为“\n”并重置
行分隔符作为方法的一部分。有更好的方法吗?我想使用Scanner,但解决方案是再次重置
行.separator
设置,这是我想要避免的。

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

见示例:

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

根据您的问题,如果是CRLF\r\f,您似乎希望跳过文件中的换行符'\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;
    }
  }
  ...

这是一个大文件,26K,可以实例化一个“大”字符串,但还没有尝试过。另一个问题是,在替换(或修复)文件(或字符串)中的所有
\f
之后,需要添加“\n”。不需要在
\r\f
处去掉“\n”,而只在
\f
本身存在的地方去掉“\n”,并在有
\r
的地方加上“\n”,以供扫描仪或其他支持文本或正则表达式的方法使用。