我有一个巨大的文件(超过 3GB),其中包含以下格式的单个长行。 “1243@818@9287@543”
然后我要分析的数据用“@”分隔。我的想法是更改默认的行尾 Java 使用的字符并设置“@”。
我正在尝试使用“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 没有完成的情况。这就是 Javadocs BufferedReader.readLine 的内容不得不说:
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/