简体   繁体   English

Java从文件中读取多个对象

[英]Java read multiple objects from a file

consider i have 2 different classes 考虑我有2个不同的类

public class A {

    String name;
    int A1;
    int A2;

}

and the other class is: 另一类是:

public class B {

    String B0;
    int B1;
    int B2;
}

and now i have a file which contains an integer, and several object of A and several of B 现在我有一个包含整数的文件,以及A的几个对象和B的几个对象

The file could be like 文件可能是这样的

3
"Jim"; 1;2
"jef";3;5
"Peter";6;7
"aa";1;1
"bb";2;3
"cc";3;4

You can consider that the 3 (in the beginning of the file)is the number of objects in class A and the rest are objects from class B. 您可以认为3 (在文件的开头)是A类中的对象数,其余是B类中的对象。

The question is, how can i read and separate all objects from the file? 问题是,我如何从文件中读取和分离所有对象?

The main problem is that i don't know how can i read the first int from the file. 主要问题是我不知道如何从文件中读取第一个int。 what i did is 我做的是

     InputStream inputFileStream = Main.class.getResourceAsStream("/inputFile.txt");
ObjectInputStream ois = new ObjectInputStream(inputStream);      
int i = ois.readInt();
     ois.close();

but it gives me an error: 但它给了我一个错误:

Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 350A4261

The main problem is that i don't know how can i read the first int from the file. 主要问题是我不知道如何从文件中读取第一个int。

You're reading a text file, not a data file, so don't use readInt() . 您正在读取文本文件,而不是数据文件,因此请勿使用readInt() Either use a BufferedReader, or my recommendation -- a Scanner object. 要么使用BufferedReader,要么使用我的建议 - 扫描程序对象。

InputStream inputFileStream = Main.class.getResourceAsStream("/inputFile.txt");
Scanner scanner = new Scanner(inputFileStream);
int int = scanner.nextInt(); // get that first int
scanner.nextLine();   // go to the next line (swallow the end-of-line token)
//.....

Then use the same Scanner to read lines. 然后使用相同的扫描仪读取线条。 Use 采用

while (scanner.hasNextLine) {
    String line = scanner.nextLine();
    // here process the line into an A or B depending on the results of a counter variable
    // then increment the counter here
}

Note that your processing will likely use the split(...) method of String to split on ; 请注意,您的处理可能会使用String的split(...)方法进行拆分; and create an array of String with the items you need. 并使用您需要的项创建一个String数组。 You'll then need to parse the int related items via Integer.parseInt(...) 然后,您需要通过Integer.parseInt(...)解析与int相关的项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM