在java中逐行读取.txt文件

时间:2015-05-07 16:08:26

标签: java file netbeans

我正在尝试读取java中的.txt文件,并创建一个列表列表,将该.txt的每一行放到另一个列表中。对于我试图这样做的每个文件都很好但是使用facebook_combined.txt.gz文件就在这个link它并没有以正确的方式执行。 示例:

如果另一个.txt文件的第一行是这样的 52 99 45 61 70 45和第二个像这样 70 80 65 91然后我的代码应该创建名为行的列表列表,行必须是这样的:

line=[[52,99,45,61,70,45][70,80,65,91]].

但对于facebook_combinded.txt文件,如果我们假设它的第一行是这样的0 10 20 30 40 50,则相同的代码会创建列表行列表,如下所示:

lines=[[0,1][0,2][0,3][0,4][0,5][0,...]].

我使用的代码如下:

 ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();

//read the file
FileInputStream fstream = new FileInputStream("C:\\Users\\facebook_combined.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

while (true)//while the file was read
{
    String line = br.readLine();//split the file into the lines
    if (line == null) 
    {
        break;//if there are no more lines left
    }

    Scanner tokenize = new Scanner(line);// split the lines into tokens and make into an arraylist
    ArrayList<String> tokens = new ArrayList<String>();

    while (tokenize.hasNext()) //while there are still more
    {
        tokens.add(tokenize.next());
    }
    lines.add(tokens);
}
    br.close();

3 个答案:

答案 0 :(得分:2)

我下载了数据集并使用7Zip解压缩了文本文件,看起来您的程序正在运行。提取文件时,数据看起来像这样(使用Notepad ++)。 。

0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
...etc...

我使用常规记事本打开文件,并且回车不可见,因此可能导致混淆(即记事本中的数据看起来像0 10 20 30 40...

编辑:更新说明

回应OP

  

你在记事本++中的数据样式是正确的,但是   正确的版本是0 10 20 30

我不确定这是否正确。谨防Occam's Razor,您假设数据应该被解析0 10 20 30,即使该文件提供非常明确的回车。如果该文件不应该有回车符,则不会有它们。类似地,它在格式化文件时似乎不是错误,因为格式始终是一对数字后跟回车符。 没有任何内容指向被解析为0 10 20 30 40 . . .

的数据

文件facebook_combined.txt看起来是图表中边缘的列表,其中每条边是两个人之间的友谊。

看起来您正在尝试阅读朋友的“圈子”,其中圆圈是数字列表。如果您下载其他tar文件“facebook.tar”,则会有几个扩展名为* .circles的文件。以下是其中一个文件的摘录。

circle0 71  215 54  61  298 229 81  253 193 97  264 29  132 110 163 259 183 334 245 222
circle1 173
circle2 155 99  327 140 116 147 144 150 270
circle3 51  83  237
circle4 125 344 295 257 55  122 223 59  268 280 84  156 258 236 250 239 69
circle5 23
circle6 337 289 93  17  111 52  137 343 192 35  326 310 214 32  115 321 209 312 41  20

这些* .circles文件似乎是您期望的格式(数字列表列表)。

答案 1 :(得分:0)

我认为你的代码有点不对劲。我通常不会使用&#34; Scanner&#34;。但也许你可以使用.split()

我不喜欢&#34;而(真实)&#34;循环,所以我建议改为:

String s;
while ((s = br.readLine()) != null) {

删除你的:

String line = br.readLine();//split the file into the lines
if (line == null) 
{
    break;//if there are no more lines left
}

然后尝试使用这样的拆分:

String[] tokenize = line.split(" ");
ArrayList<String> tokens = new ArrayList<String>();
for(String s : tokenize){
tokens.add(s);
}

答案 2 :(得分:0)

嗯,你只是说实际上.txt文件看起来像

0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8

但你需要它像

   0 10 20 30 40 50

所以我认为您需要读取所有文件,然后替换回车