使用Java解析行的最佳方法是什么? [英] What is the best way to parse a line using Java?

查看:74
本文介绍了使用Java解析行的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个小型Java应用程序,其部分工作是读取,写入和解析文本文件中的行.但是我的问题是从文本文件中提取一行,读取它,并将其分成几部分.例如,示例行是:

I'm trying to write a small Java application, and part of its job is to read, write, and parse lines from text files. My problem though is taking a line from a text file, reading it, and breaking it into parts. For example, an example line is:

Tuesday, 11/11/14 10:30:32: 3.93

我希望我的程序能够查看并填写例如string day = "tuesday"value = 3.93.

I want my program to be able to look at this and fill up for example a string day = "tuesday", and value = 3.93.

FileReader fileReader = new FileReader(itemValue);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
    stringBuffer.append(line + "\n");
    int[] value;

}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());

这是我当前拥有的代码-它将解析我的文件并逐行打印到控制台中,但是我真的不知道如何实际处理该行.我试过使用bufferedReader.readLine作为包含行的变量,但这似乎不是答案.我对Java非常陌生,这对我的编程来说是一个很大的障碍,因此,如果有人可以向我提出解决方案,那将是非常棒的.提前致谢! :)

This is the code I currently have - it will parse through my file and print out line by line into the console, but I don't really know how to actually process the line. I've tried using bufferedReader.readLine as the variable containing the line, but that doesn't seem to be the answer. I'm extremely new to Java and this is a big roadblock in my programming, so if anybody could point me toward a solution, that would be awesome. Thanks in advance! :)

我所有的数据看起来完全一样,剩下的就是这里.

All of my data looks exactly the same, here is the rest of it.

Tuesday, 11/11/14 10:29:23: 4.48
Tuesday, 11/11/14 10:29:27: 5.0
Tuesday, 11/11/14 10:29:39: 5.95
Tuesday, 11/11/14 10:29:46: 6.0
Tuesday, 11/11/14 18:07:25: 4.0
Tuesday, 11/11/14 18:07:27: 4.5
Tuesday, 11/11/14 18:07:33: 5.0
Tuesday, 11/11/14 18:07:39: 5.9
Tuesday, 11/11/14 18:07:51: 20.0

推荐答案

解析此类数据的两种最受欢迎​​的方法是String.split()和使用正则表达式.

Two of the most popular approaches to parsing this kind of data are String.split(), and using a regular expression.

使用String.split(),您可能会执行以下操作:

With String.split() you might do something like this:

while ((line = bufferedReader.readLine()) != null) {
    String[] parts = line.split("\\s+");
    // now each part of the input line (separated by whitespace) is in a different element of the parts array
}

如果您选择使用正则表达式,并且希望使用第一个和最后一个部分,则可以尝试以下正则表达式:

If you choose to use a regular expression, and you wanted the first and last parts, you might try a regular expression like:

^(A-Za-z), .*? (0-9\.)$

当然,要执行它,还需要其他代码.用谷歌搜索正则表达式".

Of course there will be other code required to execute it. Do a google search for "regular expressions".

这篇关于使用Java解析行的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆