java - 将 .txt 中的行读取到对象表中

标签 java object methods text-files

我需要帮助;我想做的是将文本文件的每一行放入对象表中。 让我们看一下例子:

我有那个文本文件:

ATI
8
10
AMX
12
15

正如我们所看到的,该文本文件包含不同类型的主板。

所以我有这个主板对象的构造函数(位于另一个类上):

motherBoard(String type, int size, int max_size){
this.type = type;
this.size = size;
this.max_size = max_size;
}

所以我想做的是创建一个对象表,其中(在本例中)表的第一个对象将包含文本文件的前 3 行。然后,表的第二个对象将包含接下来的 3 行,依此类推...

我想做的所有操作都在一个方法中...... 这是到目前为止我的代码:

public static CarteMere[] chargerEnMemoire(String nomFichier) throws IOException{
    CarteMere[] newCarteMere = new CarteMere[0];
    try {
        FileReader reader = new FileReader( "liste.txt" );
        BufferedReader buffer = new BufferedReader( reader );
        int nmLines = 0;
        while ( buffer.ready() ) {
            nmLines++; // To evaluate the size of the table
        }
        buffer.close();
        newCarteMere = new CarteMere[nmLines/3];
        for(int i=0; i<(nmLines/3);i++){

        }
    } catch ( FileNotFoundException e ) {
        System.out.println( e.getMessage() );
    } catch ( IOException e ) {
        System.out.println( e.getMessage() );
    }

    return newCarteMere;
}

这就是我需要插入的地方......

最佳答案

从您所知道的开始,您有一个文件,它包含三行数据,其中一行是字符串,另外两行是数字。

你有一个代表该数据的类,总是更容易在可能的情况下将数据存储在对象中,所以你可以做类似的事情......

try (BufferedReader br = new BufferedReader(new FileReader("liste.txt"))) {
    String name = br.readLine();
    int size = Integer.parseInt(br.readLine());
    int max = Integer.parseInt(br.readLine());

    Motherboard mb = new MotherBoard(name, size, max);
    // Add it to a List or what ever else you want to do it...
} catch (IOException exp) {
    exp.printStackTrace();
}

关于java - 将 .txt 中的行读取到对象表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27394456/

相关文章:

java - 为什么 images.google.com GET 请求具有如此不可读的形式?

java - LeetCode正则表达式问题中重叠子问题的可视化以及DP的使用

java - 我应该如何将功能划分为 Java 类?

java - 为什么我不能在 Java 中的 try block 后打印到控制台?

python - 输出类定义为列表的所有成员

java - 使用自定义类作为 HashMap 中的键但无法搜索键

JavaScript - 将对象添加到对象中

c++ - 如何使存储在 vector 中的对象中的数据唯一?

java - 在 Java String 方法中获取 int 变量

c# - 无法从 C# WPF 中的另一个窗口调用方法