我正在尝试编写一个Java方法,它将逐行解析一个文本文件。在下面的示例中,我想把行前面的数字作为一个键值,使用FFM数字作为下一个键字段,直到alpha数字字符(在下面的情况下是CH,它不是键序列的一部分)。
107458982 FFM00000000000713432CH一旦钥匙分开,我就想拿着它们,做一个键字段。
最后,每一行都会有一个键字段,实际上是19个字节长。这是关键字段在每一行末尾的样子。我希望将这些关键字段推到ArrayList上,以便将它们与具有类似类型结构的另一个txt文件进行比较。我原以为这会很容易,但结果比我想的要困难得多。
Key Filed --> 107458982FFM00000000000713432 在本例中,我的文本文件每一行都有一个空行,所以我需要跳过下面代码中没有的空行。
问题:如何将该文件尽可能简单、快速地解析到我的密钥字段中?
代码:
private ArrayList<String> scannerRead4(String inFileUsed) {
ArrayList<String> tempList = null;
try {
BufferedReader in = new BufferedReader(new FileReader(inFileUsed));
try {
String line;
while ((line = in.readLine()) != null) {
String[] s = line.split(" ");
for (int index=0;index<line.length()-1; index++) {
System.out.println("s: " + s[index]);
}
//tempList = new ArrayList<String>(Arrays.asList(line.split(" ")));
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return tempList;
}需要解析的文件上下文
107458982 FFM00000000000713432CH
107462291 FFM00000000001835472T
107462291 FFM00000000002200570T
107462291 FFM00000000002432274T
108018296 FFM00000000001431509T
108018296 FFM00000000001553064T
108122386 FFM00000000001211063T
108122386 FFM00000000001862517T
108491927 FFM00000000004556330T
108500569 FFM00000000001682124
108500569 FFM00000000002023040
108523927 FFM00000000000611642
108523927 FFM00000000002162127
108768840 FFM00000000001360865T
108768840 FFM00000000001796191T
108774203 FFM00000000001821871T
108774203 FFM00000000001946211T
108774203 FFM00000000001914770T 发布于 2014-04-10 02:55:12
如果您计划使用键/值设计,请使用HashMap:
HashMap<String, String> map = new HashMap<String, String>();然后,不要使用readLine(),而是使用read()。你想一次读一个字符,以便尽可能的高效。如果您一次读取一行,则必须解析行字符串,这是浪费时间。您需要两个独立的内部循环来跳过空格并查找值。外循环将查找密钥。
另外,使用StringBuffer而不是String。当您计划连接大量字符串或字符时,这是很好的。
这个伪代码假设您的文件是正确的(没有缺少键或值)。
StringBuffer key, value;
char c;
while ((c= in.read()) != null) {
key = new StringBuffer();
if(c != " "){
key.append(c);
}else{
value = new StringBuffer();
while ((c= in.read()) == " ");//skip all the spaces
value.append(c);//add last char found
//find rest of value until new line
//may want to use System.getProperty("line.separator") or whatever the char value of new line is.
while ((c= in.read()) != null && c != "\n") {
value.append(c);//add last char found
}
map.put(key.toString(), value.toString());//map it all together
}
}注意到:将其视为伪代码。我还没有亲自测试过,但这应该是一个很好的方法。
https://stackoverflow.com/questions/22976637
复制相似问题