gpt4 book ai didi

java - BufferedReader 被不同的行分隔符搞乱了

转载 作者:行者123 更新时间:2023-12-01 10:04:06 24 4
gpt4 key购买 nike

我有一个缓冲阅读器正在传输文件。目前有两种情况:

它正在流式传输在一台 PC 上生成的文件,我们将其称为 File1。它正在流式传输另一台计算机上生成的文件,我们将其称为 File2。

我假设我的问题是由 EOL 引起的。

BufferedReader 会读取这两个文件,但对于 File2,它会为每个新行读取一个额外的空行。

此外,当我使用 line.equalsIgnoreCase("abc") 比较该行时,鉴于该行是 "abc" 它不会返回 true .

将此代码与两个链接中提供的两个文件一起使用来复制问题:

public class JavaApplication {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
File file = new File("C:/Users/User/Downloads/html (2).htm");
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String line = "";

while ((line = in.readLine()) != null) {
System.out.println(line);
}
}

File1 , File2

注意第二个文件如何在每行后打印一个空行...

我一直在寻找、尝试、寻找、尝试,但找不到解决方案。

有什么想法可以解决这个问题吗? (尤其是比较的事情?)

最佳答案

对我有用。

public class CRTest
{
static StringReader test = new StringReader( "Line 1\rLine 2\rLine 3\r" );
public static void main(String[] args) throws IOException {
BufferedReader buf = new BufferedReader( test );
for( String line = null; (line = buf.readLine()) != null; )
System.out.println( line );
}
}

打印:

run:
Line 1
Line 2
Line 3
BUILD SUCCESSFUL (total time: 1 second)

正如 Joop 所说,我认为您混淆了哪个文件不起作用。请使用上面的骨架创建一个MCVE并向我们​​准确展示哪些文件输入不适合您。

<小时/>

由于您似乎有一个包含反向 \r\n 行的文件,这是我第一次尝试修复。请测试一下,我还没试过。您需要使用此类包装 InputStreamReader,然后像平常一样将 BufferedReader 包装在外部。

class CRFix extends Reader
{

private final Reader reader;
private boolean readNL = false;

public CRFix( Reader reader ) {
this.reader = reader;
}

@Override
public int read( char[] cbuf, int off, int len )
throws IOException
{
for( int i = off; i < off+len; i++ ) {
int c = reader.read();
if( c == -1 )
if( i == off ) return -1;
else return i-off-1;
if( c == '\r' && readNL ) {
readNL = false;
c = reader.read();
}
if( c == '\n' )
readNL = true;
else
readNL = false;
cbuf[i] = (char)c;
}
return len;
}

@Override
public void close()
throws IOException
{
reader.close();
}

}

关于java - BufferedReader 被不同的行分隔符搞乱了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36582103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com