如何从 java 中的文件保存信息

how to save information from a file in java

我很想读一个文件,假设它有 3 行:

2

Berlin 0 2 2 10000 300

Nilreb 0 2 2 10000 300

第一个整数表示我有多少个名字(行)。

第 2 行和第 3 行显示有关两个 post 办公室的信息。

他们我想读取每一行并保存数据。

我必须创建 post 个办公室,它们的名字是:Berlin 和 Nilreb。

谁能帮帮我?

到目前为止我已经这样做了:

public static void read_files() throws IOException{
    Scanner in = new Scanner(new File("offices")); //open and read the file
    int num_of_lines = in.nextInt();
    while(in.hasNext()){
        String offices = in.nextLine();
    }

我想我明白了:你能检查一下它是否正确吗:

public static void read_files() throws IOException{
        Scanner in = new Scanner(new File("offices"));
        int num_of_lines = in.nextInt();
        String[] office = new String[num_of_lines];
        while(in.hasNext()){
            for(int = 0; i < num_of_lines; i++){
                office[i] = in.next();
                }
  1. 列表项

要阅读文件,我建议您使用 ArrayList:

Scanner s = new Scanner(new File(//Here the path of your file));

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

while (s.hasNext())
{
    list.add(s.nextLine());
}

现在,在您的 ArrayList 中,您将拥有文件的所有行。所以,现在,您可以使用 for 循环遍历所有 post 个办公室(我从索引 1 开始,因为第一行是文件中有多少 post 个办公室,您将不需要使用此方法)和 split 它们来获取有关它们的所有信息。例如,在 Strings 数组的位置 0 中,您将拥有 post 办公室的名称,而在其余位置 (1,2,3,4...) 中,其余你的值存储在你的文件中(一个值由 space 在你的行中)。像这样:

for(int i = 1; i < list.size(); i++)
{
   String[] line  = list.get(i).split(" ");

   System.out.println("The name of this post office is " + line[0]);
}

编辑: 我现在在上面的评论中看到您想为每一行创建一个 class。然后你可以执行(在 for 循环内,而不是 System.out.println)我放在下面的代码(假设你的 class 将是 PostOffice):

PostOffice postOffice = new PostOffice(line[0],line[1],line[2],line[3],line[4],line[5]);

注意:如果您不了解我的代码,请告诉我。

希望对您有所帮助!