15

我想将一个文本文件读入一个数组。我怎样才能做到这一点?

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

5 回答 5

11

使用 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[]{});
于 2012-04-21T10:09:52.837 回答
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[]{});
于 2018-05-12T15:52:20.363 回答
3

改用 a 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();
于 2012-04-21T10:11:02.003 回答
2

如果你不允许这样做 dtechs 方式,并使用 ArrayList,请阅读 2 次:第一次,获取声明数组的行数,第二次填充它。

于 2012-04-21T10:13:32.833 回答
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();
于 2018-04-23T05:20:28.200 回答