Answer the question
In order to leave comments, you need to log in
Why is the first element of the array empty?
There is a code in which I write objects to a file in three ways and then in another class I get them from the file
public class WriteObject
{
public static void main(String[] args) throws IOException
{
// first
Person person1 = new Person(1, "Mike");
Person person2 = new Person(2, "Bobe");
FileOutputStream fos = new FileOutputStream("people.bin");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person1);
oos.writeObject(person2);
oos.close();
// Second
Person[] people = new Person[3];
Scanner scanner = new Scanner(System.in);
String name;
for(int i = 0; i < people.length; ++i)
{
name = scanner.nextLine();
people[i]= new Person(i + 1, name);
}
FileOutputStream fileOutputStream = new FileOutputStream("person.bin");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeInt(people.length);
for(Person person : people)
{
objectOutputStream.writeObject(person);
}
objectOutputStream.close();
// Third
System.out.println("Enter len of third ");
int lenOfThird = scanner.nextInt(); // 47
Person[] thirdTimes = new Person[lenOfThird];
for(int i = 0; i < lenOfThird; ++i)
{
name = scanner.nextLine();
thirdTimes[i]= new Person(i + 1, name);
}
FileOutputStream fileOutputStreamOfThird = new FileOutputStream("third.bin");
ObjectOutputStream objectOutputStreamOfThird = new ObjectOutputStream(fileOutputStreamOfThird);
objectOutputStreamOfThird.writeObject(thirdTimes);
objectOutputStreamOfThird.close();
scanner.close();
}
}
Answer the question
In order to leave comments, you need to log in
and
name = scanner.nextLine();
for(int i = 0; i < lenOfThird; ++i)
{
name = scanner.nextLine();
thirdTimes[i]= new Person(i + 1, name);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question