解析Java中文本文件中的数据 [英] Parse data from text file in Java

查看:811
本文介绍了解析Java中文本文件中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Java创建一个解析器,以帮助我从文本文件中获取一些详细信息.

I'm trying to create a parser in Java that would help me to get some details from a text file.

文件中的数据看起来像这样,但有更多条目:

The data in the file looks like this, but with more entries:

. 
http://www.someurl1.com/
PERSONAL ADDRESS: Mozart, W.A.; Some address 1, Austria; email: mymail1@mail.com

. 
http://www.someurl2.com/
PERSONAL ADDRESS: Beethoven, L.V.; Some address 2, Germany; email: mymail2@mail.com

如您所见,数据始终遵循一种模式,而我想获得的只是每个条目的名称和电子邮件.可能的良好输出是这样:

As you can see, the data always respects a pattern, and what I would like to get is just the name and the e-mail for every entry. A possible good output would be this:

Mozart, W.A. ; mymail1@mail.com
Beethoven, L.V. ; mymail2@mail.com

每个条目均以.开头,后跟第一行中的空格.然后,在圆点上方的下一行中,有URL.在下一行中,还有更多数据:名称,地址和电子邮件,所有数据均用;分隔.

Every entry starts with a . followed by a space in the first line. Then in the next line above the dot, there's the URL. In the following line, there's more data: name, address and e-mail, all separated by a ;.

这并不难,但是我遇到了一些麻烦.我创建了一个Main类,在其中将文本文件读取到String.但是,如果我应该尝试使用正则表达式或只是寻找;,那么我真的不知道在Java中解析此类内容的最佳方法是什么.

This isn't hard but I'm having some troubles starting. I've created a Main class in which I read the text file to a String. But then I really don't know what's the best way to parse something like this in Java, if I should try to use regular expressions or just get looking for the ;.

推荐答案

逐行读取文本文件,然后根据该行执行操作.

Read in the text file line by line and then do an action based on that line.

BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
   // process the line.
   if (line.equals(". "))
   {
       // Do something with first line
       line = br.readLine()
       // Do something with second line
       line = br.readLine()
       // Split up the third line by space 
       String split[]= StringUtils.split(line); // split[1] = "Mozart," so you may need to do a little more work there
   }
}
br.close();

这篇关于解析Java中文本文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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