【问题标题】:how to save information from a file in java如何在java中保存文件中的信息
【发布时间】:2015-06-12 23:53:08
【问题描述】:

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

2

Berlin 0 2 2 10000 300

Nilreb 0 2 2 10000 300

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

第 2 行和第 3 行显示有关两个邮局的信息。

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

我必须创建以它们为名称的邮局: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();
    }

【问题讨论】:

  • Scanner 也有nextInt 和其他类似的对你有用的功能。
  • 你要创建一个 PostOfficer 类来存储数据吗?
  • 是的,我正在创建 PostOffice 类

标签: java string file io


【解决方案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 循环遍历您拥有的所有邮局(我从索引 1 开始,因为第一行是文件中有多少邮局的行,您不需要它这个方法)和split他们来获取关于他们的所有信息。例如,在Strings 数组的位置 0 中,您将拥有邮局的名称,而在其余位置 (1,2,3,4...) 中,其余值存储在您的文件(一行中的空格一个值)。像这样:

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]);
}

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

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

注意:如果您对我的代码有什么不明白的地方,请告诉我。

希望对你有帮助!

【讨论】:

    【解决方案2】:

    我想我明白了:你可以检查它是否正确:

    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. 列表项

    【讨论】:

      猜你喜欢
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多