我需要帮助;我想做的是将文本文件的每一行放入对象表中。 让我们看一下例子:
我有那个文本文件:
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/