java - 在java中错误地逐行读取.txt文件

标签 java file netbeans

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

如果另一个.txt文件的第一行是这样的 52 99 45 61 70 45 第二个像这样 70 80 65 91 那么我的代码应该创建名为lines的列表列表,并且lines必须如下所示:

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();

最佳答案

我下载了数据集并使用 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

You are right for the way that the data look like in notepad++ but the right version is 0 10 20 30

我不确定这是否正确。谨防Occam's Razor ,您假设应该解析数据 0 10 20 30 即使文件提供了非常明确的回车符。如果文件不应该包含回车符,那么它就不会包含回车符。同样,文件格式似乎也不是错误,因为格式始终是一对数字后跟回车符。 没有任何内容表明数据被解析为 0 10 20 30 40 。 。 .

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

您似乎正在尝试阅读 friend 的“圈子”,其中圈子是数字列表。如果您下载另一个 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 文件似乎是您期望的格式(数字列表的列表)。

关于java - 在java中错误地逐行读取.txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30106393/

相关文章:

java - 为什么当我将元素从一维数组传输到二维数组时,在获取上一个循环生成的最后一个一维数组时

java - NetBeans 中的命令行参数

java - 在 netbeans 中检索当前打开的文件或项目的位置

eclipse - 学术界如何看待eclipse ide?

java - Activity.class - 类文件编辑器 : The JAR file c:\sdk\platforms\android-17\android. jar 没有源附件

java - 在简单框架中使用标签属性过滤标签

java - 背包算法,大容量

command-line - 在 Vim 中打开 URL 的最佳方法

file - 什么时候文件不是文件系统对象?

JavaFX - 如何获取选项卡、按钮等的背景颜色