将文本文件读入数组

17

我想将一个文本文件读入到一个数组中。我该如何做到?

data = new String[lines.size]

我不想在数组中硬编码10。

BufferedReader bufferedReader = new BufferedReader(new FileReader(myfile));
String []data;
data = new String[10]; // <= how can I do that? data = new String[lines.size]

for (int i=0; i<lines.size(); i++) {
    data[i] = abc.readLine();
    System.out.println(data[i]);
}
abc.close();

1
为什么要使用数组?为什么不用其他容器? - Mat
2
因为我的老师说必须使用数组来存储文本文件的数据。 - heyman
6
伟大的老师,伟大的学生。 - Lucifer
5个回答

13

使用ArrayList或其他动态数据结构:

BufferedReader abc = new BufferedReader(new FileReader(myfile));
List<String> lines = new ArrayList<String>();

while((String line = abc.readLine()) != null) {
    lines.add(line);
    System.out.println(data);
}
abc.close();

// If you want to convert to a String[]
String[] data = lines.toArray(new String[]{});

6
可以的!以下是内容的翻译:原文:it work! thank! 翻译:它起作用了!谢谢!原文:Also, while((String line = abc.readLine()) not work, It should be String line; while((line = abc.readLine()) then can work:] 翻译:而且,while((String line = abc.readLine())不起作用,应该是String line;while((line = abc.readLine())才能起作用。 - heyman

4
File txt = new File("file.txt");
Scanner scan = new Scanner(txt);
ArrayList<String> data = new ArrayList<String>() ;
while(scan.hasNextLine()){
    data.add(scan.nextLine());
}
System.out.println(data);
String[] simpleArray = data.toArray(new String[]{});

3
使用 List 代替。最后,如果需要的话,可以将其转换回 String[]
BufferedReader abc = new BufferedReader(new FileReader(myfile));
List<String> data = new ArrayList<String>();
String s;
while((s=abc.readLine())!=null) {
    data.add(s);
    System.out.println(s);
}
abc.close();

2
您可以像这样做:
  BufferedReader reader = new BufferedReader(new FileReader("file.text"));
    int Counter = 1;
    String line;
    while ((line = reader.readLine()) != null) {
        //read the line 
        Scanner scanner = new Scanner(line);
       //now split line using char you want and save it to array
        for (String token : line.split("@")) {
            //add element to array here 
            System.out.println(token);
        }
    }
    reader.close();

2

如果不能按照dtechs的方式使用,而是要用ArrayList,需要读取两次:第一次读取获取行数以声明数组,第二次读取填充数组。


如果只允许使用数组(或者你正在使用C语言编程),那确实是你应该采取的方法。 - dtech
1
或者,您可以模拟List的操作,并根据需要增加数组的大小,使用arrayCopy()复制所有项目,避免两次读取文件的昂贵操作(尽管如果是小文件,则不会有太大影响)。 - Guillaume Polet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接