我正在使用JAVA开发Android应用程序。
我有一个像这样的文本文件在互联网上
它就像这样显示
Name="testMusic1" Uri="http://www2.compute.com.tw/test1.mp3" Author="chali" Length=125 Icon="xxx" Lang="台语"
Name="testMusic2" Uri="http://www2.compute.com.tw/test2.mp3" Author="yflin" Length=123 Icon="xxx" Lang="国语"
Name="testMusic3" Uri="http://www2.compute.com.tw/test3.mp3" Author="kkj" Length=132 Icon="xxx" Lang="英文"
但据我所知,我知道如何解析.csv文件,我也知道如何解析xml文件,使用XPath表达,
但!是否有任何更简单的方法来解析像这样的文本文件? 是否有任何好的API我可以用来解析这样的文本文件??? 或使用JAVA扫描仪并使用Delimiter ???
有没有用JAVA编写的例子?因为我真的不能再抬头了...... 已经搜索/调查了很长时间。 有人能帮助我吗?
答案 0 :(得分:2)
这是一个完整的测试工作程序。只需将此文件放在music.txt所在的位置即可运行。它还使用Scanner
类。
import java.io.*;
import java.util.*;
public class Program {
public static void main(String[] args) throws Exception{
FileReader file = new FileReader("music.txt");
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String line = scanner.nextLine().trim();
String[] tokens = line.split("\\s+");
for(int i = 0; i < tokens.length; i++){
String[] elements = tokens[i].split("=");
System.out.println(elements[0] + ": " + elements[1]);
}
System.out.println();
}
scanner.close();
}
}
示例输出
Name: "testMusic1"
Uri: "http://www2.compute.com.tw/test1.mp3"
Author: "chali"
Length: 125
Icon: "xxx"
Lang: "test1"
Name: "testMusic2"
Uri: "http://www2.compute.com.tw/test2.mp3"
Author: "yflin"
Length: 123
Icon: "xxx"
Lang: "test2"
Name: "testMusic3"
Uri: "http://www2.compute.com.tw/test3.mp3"
Author: "kkj"
Length: 132
Icon: "xxx"
Lang: "test3"
VVV
答案 1 :(得分:1)
一种可能性是String.split()。
实施例
public class Split {
static final String s =
"Name=\"testMusic1\" Uri=\"http://www2.compute.com.tw/test1.mp3\" Author=\"chali\"";
public static void main (String[] args) {
String[] nameValuePairs = s.split("\\s+"); // Split each item in string on whitespace (\s+)
for (int i=0; i < nameValuePairs.length; i++) {
String[] nv = nameValuePairs[i].split("="); // Split the resulting name/value pair on "="
System.out.println ("pair[" + i + "]: (" + nameValuePairs[i] + "), name=" + nv[0] + ", value=" + nv[1] + ".");
}
}
}
示例输出:
pair[0]: (Name="testMusic1"), name="Name, value="testMusic1".
pair[1]: (Uri="http://www2.compute.com.tw/test1.mp3"), name=Uri, value="http://www2.compute.com.tw/test1.mp3".
pair[2]: (Author="chali"), name=Author, value="chali".
答案 2 :(得分:0)
这里的问题是你没有为你的输入提供正确的语法,而设计一个基于解析器的例子就是......狡猾。
例如,如果我们假设所有示例都是这样的,那么String.split("\\s+")
后跟String.split("=")
将完成这项工作。或者您可以使用Scanner
执行相同的操作。
但如果其他例子(你还没有看到)有点不同,这可能行不通。例如:
简而言之,这些示例中有足够的信息可供您(或任何人)实施适用于所有输入的解析器。