在Java中读取选项卡分隔的文件
我有以下代码来读取Java中的制表符分隔文件:在Java中读取选项卡分隔的文件,java,csv,file-io,Java,Csv,File Io,我有以下代码来读取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" + val
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]);
}
但它打印的是1而不是文件内容。这里怎么了?
示例文件中的一行内容如下:
{Amy Grant}{/m/0n8vzn2}{...}
写
\t
而不是\\t
。那才是你想要的
String[] values = str.split("\t");
我在我的一些项目中使用了它,它把工作做得相当好
尝试System.out.println(Arrays.asList(values))
这管用!但我需要单独访问这些字段。你能告诉我我的密码里写的是什么吗
我怀疑您正在获得一个索引AutofBoundsException
。你得到的错误很重要,如果你忽视它,你就不可能希望解决问题
这意味着您只有一个字段集
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"));
您要拆分的字符串文本是什么?有很多TSV和CSV解析器库-我强烈建议您使用其中的一个,而不是滚动自己的。请尝试
System.out.println(Arrays.asList(values))代码>@EshaGhosh你确定文件是按标签分开的吗?@EshaGhosh你能告诉我们标签在哪里使用原始问题吗?它们不会出现在评论中。它们不是等价的吗?不会\\解析为\将\t留给您?这意味着在两个字符\t
上拆分,而不是在选项卡上。“\”是一个错误。“\t”是一个特殊字符,制表符。“\\t”是“\t”,但不是选项卡。非常感谢。不截断空字段对我帮助很大。