gpt4 book ai didi

java - 如何在 java 中处理具有不同行分隔符的文件?

转载 作者:行者123 更新时间:2023-11-29 03:15:21 24 4
gpt4 key购买 nike

我有一个巨大的文件(超过 3GB),其中包含以下格式的单个长行。“1243@818@9287@543”

然后我要分析的数据用“@”隔开。我的想法是更改默认的行尾Java ans 集“@”使用的字符。

我正在尝试使用以下代码使用“System.setProperty("line.separator", "@");"但不起作用,因为正在打印完整的行,对于此测试,我希望作为输出。

1243
818
9287
543

如何将默认行分隔符更改为“@”?

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
System.setProperty("line.separator", "@");

File testFile = new File("./Mypath/myfile");
BufferedReader br = new BufferedReader(new FileReader(testFile));
for(String line; (line = br.readLine()) != null; ) {
// Process each the line.
System.out.println(line);
}
}

}

在此先感谢您的帮助。

最佳答案

Then the data I want to analyze is separated with "@". My idea is to change the default end of line character used by Java ans set "@".

我不会那样做,因为它可能会破坏天知道还有什么依赖于 line.separator。

至于为什么这不起作用,我很遗憾地说这是 RTFM 没有完成的情况。这就是 BufferedReader.readLine 的 Javadocs不得不说:

public String readLine()
throws IOException
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
Throws: IOException - If an I/O error occurs

readLine() 方法的 API 文档清楚地表明它查找 '\n''\r'。它没有说它取决于 line.separator

line.separator 属性仅用于开发需要可移植的、独立于平台的机制来标识行分隔符的 API。就这些。此系统属性不是用于控制 Java 的 IO 类的内部机制。

我认为你把事情复杂化了。只需以旧方式读取缓冲区中的 n 个字符(比如 1024KB),然后扫描每个“@”分隔符即可。这引入了复杂情况,例如正常情况下“@”分隔符之间的数据在缓冲区之间拆分。

所以,我建议只从缓冲阅读器中读取一个字符(这还不错,而且通常不会过度影响 IO,因为缓冲阅读器确实... tada... 为您缓冲。)

将每个字符抽取到一个字符串生成器中,每次你找到一个“@”分隔符时,你将字符串生成器的内容刷新到标准输出或其他任何东西(因为这将代表你的“@”文件中的一个数据。)

首先让算法正常工作。稍后优化。这是下面的伪代码,不保证没有编译错误。您应该能够用语法正确的 Java 轻松充实它:

File testFile = new File("./Mypath/myfile");
int buffer_size = 1024 * 1024
BufferedReader br = new BufferedReader(new FileReader(testFile), buffer_size);

StringBuilder bld = StringBuilder();
int c = br.read();

while(c != -1){
char z = (char)c;
if(z == '@'){
System.out.println(bld);
if(bld.length() > 0){
bld.delete(0, bld.length() - 1);
}
} else {
bld.append(z);
}
}

关于java - 如何在 java 中处理具有不同行分隔符的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049443/

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