我有以下代码来读取Java中的制表符分隔文件:
while ((str = in.readLine()) != null) {
if (str.trim().length() == 0) {
continue;
}
String[] values = str.split("\\t");
System.out.println("Printing file content:");
System.out.println("First field" + values[0] + "Next field" + values[1]);
}
Run Code Online (Sandbox Code Playgroud)
但它打印1而不是文件内容.这有什么不对?示例文件中的一行如下所示:
{Amy Grant}{/m/0n8vzn2}{...}
Run Code Online (Sandbox Code Playgroud)
Pet*_*rey 13
尝试
System.out.println(Arrays.asList(values));这有效!但我需要单独访问这些字段.你能告诉我我的代码中有什么问题吗?
我怀疑你得到了IndexOutOfBoundsException.您获得的错误很重要,如果忽略它,您无法解决问题.
这意味着您只有一个字段集.
String[] values = str.split("\\t", -1); // don't truncate empty fields
System.out.println("Printing file content:");
System.out.println("First field" + values[0] +
(values.length > 1 ? ", Next field" + values[1] : " there is no second field"));
Run Code Online (Sandbox Code Playgroud)
写\t而不是\\t.这将是你想要的更多
String[] values = str.split("\t");
Run Code Online (Sandbox Code Playgroud)
我在我的一些项目中使用了http://sourceforge.net/projects/opencsv/,它可以很好地完成工作.
| 归档时间: |
|
| 查看次数: |
24687 次 |
| 最近记录: |