读取制表符分隔的文本文件 java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18331696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reading tab delimited textfile java
提问by Wayne
10
aaa aaa aaa
bbb bbb bbb
ccc ccc ccc
ddd ddd ddd
I have a textfile that Im trying to read with tab delimiters. whenever i read the file, i get an arrayindexoutofbound error after the 10. i search online and found that i have to add a -1 behind the \t but i still get the same error.
我有一个文本文件,我试图用制表符分隔符读取它。每当我读取文件时,我都会在 10 之后收到一个 arrayindexoutofbound 错误。我在网上搜索并发现我必须在 \t 后面添加一个 -1,但我仍然遇到相同的错误。
try{
Scanner scan = new Scanner(new File("1.txt"));
String line="";
int readline = Integer.parseInt(scan.nextLine());//
while (scan.hasNextLine())
{
line = scan.nextLine();
if(line.equals("ccc"))
{
break;
}
String[] split=line.split("\t");
array.add(split);
}
回答by Marc
This way your code loses this ugly break (break are most of the time avoidable ...)
这样你的代码就会失去这个丑陋的中断(中断在大多数情况下是可以避免的......)
try{
Scanner scan = new Scanner(new File("1.txt"));
String line="";
int readline = Integer.parseInt(scan.nextLine());//
while (scan.hasNextLine())
{
line = scan.nextLine();
if(!line.equals("aaa")){
String[] split=line.split("\t");
array.add(split);
}
}
And about your problem I think you are initializing your array with the integer on the first line but it is 10 and you have 12 elements. Thus the index out of bounds but your question remains unclear ...
关于你的问题,我认为你正在用第一行的整数初始化你的数组,但它是 10,你有 12 个元素。因此索引越界,但您的问题仍然不清楚......
回答by Ruchira Gayan Ranaweera
If you are use Scanner
here no need to split
, you can use next()
here as follows
如果你在Scanner
这里使用不需要split
,你可以next()
在这里使用如下
Scanner sc=new Scanner(new FileReader("D:\test.txt"));
while (sc.hasNextLine()){
System.out.println(sc.next());
}