3

consider i have 2 different classes

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

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 the3 (in the beginning of the file)is the number of objects in class A and the rest are objects from class 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. 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
2
  • Your question is a multi-step question, and the steps include 1) reading lines from a file, 2 using loops to read in the first x A types, then a while loop to read the remaining lines 3) converting each line to an A or B type. So.... where exactly are you stuck? Show what you've tried please. Commented Apr 3, 2016 at 19:35
  • @HovercraftFullOfEels i have edited my question Commented Apr 3, 2016 at 19:43

1 Answer 1

0

The main problem is that i don't know how can i read the first int from the file.

You're reading a text file, not a data file, so don't use readInt(). Either use a BufferedReader, or my recommendation -- a Scanner object.

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 ; and create an array of String with the items you need. You'll then need to parse the int related items via Integer.parseInt(...)

Sign up to request clarification or add additional context in comments.

3 Comments

but when i go to the objects i have to change again my streaminput. right?
@KamyarParastesh: heck no. Use the same Scanner. See edit above. You will want to try something and see what happens.
@KamyarParastesh: Any further questions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.