我是Java的新手,我想知道如何读取.txt文件,然后将每一行放入数组单元格中。
.txt文件的格式必须如下所示:

car //goes in array[0]
boat //goes in array[1]
ship //goes in array[2]
airplane //goes in array[3]
//...and so on..


我已经尝试创建以这种方式实现的ReadFile类:

import java.io.*;
import java.util.*;
public class ReadFile {
    private Scanner x;

public void open(){
    try{
        x = new Scanner(new File("time_table_data.txt"));
    }catch(Exception e){
        System.out.println("Could Not Create The File");
    }
}

public String read(){
    String s = "";
    while(x.hasNext()){
        String a = x.next();
        s = a.format("%s\n",a);
    }
    return s;
}


public void close(){
    x.close();
}


}

最佳答案

问题是您不知道会出现多少个单词。为了解决这个问题,您可以使用ArrayList。

List<String> entries = new ArrayList<String>();
while (scanner.hasNext())
{
    entries.add(scanner.nextLine());
}
System.out.println(entries);


使用get(int index)方法访问它们:

String test = entries.get(0); // This will be "car"

关于java - 将.text文件数据放入数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20813848/

10-11 22:28
查看更多