This question already has answers here:
How to write data with FileOutputStream without losing old data?
(2 answers)
Closed 5 years ago.
I am writing to a stream file in Java. I have read if I want to append I need to override WriteStreamHeader. But even after doing so, I am not able to get free from StreamCorruptedException.
class AppendingObjectOutputStream extends ObjectOutputStream {
public AppendingObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
protected void writeStreamHeader() throws IOException {
reset();
}
}
class Student implements Operations,Serializable
{
private static final long serialVersionUID = 1L;
private int studid;
private String sname;
private int sage;
private long contact;
public Student()
{
studid = 0;
sname = null;
sage = 0;
contact = 0;
}
public void add(Scanner sc)
{
System.out.print("Enter student id: ");
studid = Integer.parseInt(sc.nextLine());
System.out.print("Enter student name: ");
sname = sc.nextLine();
System.out.print("Enter student age: ");
sage = Integer.parseInt(sc.nextLine());
System.out.print("Enter student's contact number: ");
contact=Long.parseLong(sc.nextLine());
}
public void show()
{
System.out.println("Student's details:");
System.out.println("Id no: "+studid);
System.out.println("Name :" + sname);
System.out.println("Age :" + sage);
System.out.println("Contact No. :" + contact);
}
}
class Admin
{
public void addstu(Scanner sc)
{
try
{
Student s = new Student();
s.add(sc);
boolean b = true;
FileInputStream fis = null;
try{
fis = new FileInputStream("student.ser");
fis.close();
}
catch (FileNotFoundException e)
{
b = false;
}
FileOutputStream fos = new FileOutputStream("student.ser");
ObjectOutputStream oos =null;
if(b == true)
{
System.out.println("Appending objects");
oos = new AppendingObjectOutputStream(fos);
}
else
{
System.out.println("Writing objects");
oos = new ObjectOutputStream(fos);
}
oos.writeObject(s);
oos.close();
fos.close();
System.out.println("Student successfully inserted");
fis = new FileInputStream("student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student result = (Student) ois.readObject();
result.show();
ois.close();
fis.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void displayallstu()
{
try
{
FileInputStream fis = new FileInputStream("student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println("Student's List");
try{
while(true)
{
Student result = (Student) ois.readObject();
result.show();
}
}
catch (EOFException e) {
System.out.println("!!End of file!!");
}
finally{
ois.close();
fis.close();}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
It is called from main and executes properly when addstu() is called for the first time, but when called for next time, displays Successfully Inserted message, but throws exception while reading.
java.io.StreamCorruptedException: invalid stream header: 79737200
What you first generate is:
stream header
student
Then you are overwriting this with:
reset
student
which cannot be read since you’re missing the stream header. You want the following in the file:
stream header
student
reset
student
To get this, you will need to open the output stream in append mode after the file has been created the first time. Since you already have a Boolean indicating if this is necessary, just pass that to the constructor:
FileOutputStream fos = new FileOutputStream("student.ser", b);
Related
This question already has answers here:
Unhandled exception type Exception
(2 answers)
Closed 9 months ago.
CourseConsole class
public class CourseConsole {
private Course Course;
private Seminar seminar;
private InputStreamReader reader;
private BufferedReader br;
private File file;
public Writer output;
private Scanner scanner;
public Course inputCourse() {
System.out.println("======inputing the course======");
//file = new File("Files1/Courses.txt");
//Creating a Scanner object
//Scanner sc = new Scanner(file);
scanner= new Scanner(System.in);
Course course = new Course();
CourseId(course);
CourseName(course);
Coursefee(course);
SeminarId(course);
return course;
}
public void CourseId(Course course) {
{
System.out.println("Please enter the Course No:");
try {
course.setId(scanner.nextInt());
if (course.getId() == 0) {
CourseId(course);
System.out.println("You have entered an invalid value!");
}
} catch (InputMismatchException e) {
System.out.println("Incorrect data");
course.setId(0);
}
System.out
.println("==================================================================================");
}
}
public void CourseName(Course course) {
System.out.println(" enter the Course name:");
try {
course.setName(scanner.next());
if (course.getName() == null
|| course.getName().trim().equals("")) {
CourseName(course);
System.out.println("You have entered an invalid value!");
}
} catch (InputMismatchException e) {
System.out.println("Your data format is incorrect:");
course.setName(null);
}
System.out
.println("==================================================================================");
}
public void Coursefee(Course course) {
System.out.println("enter the Course fee");
try {
course.setfees(scanner.nextInt());
if (course.getfees() == 0) {
Coursefee(course);
System.out.println("You have entered an invalid value!");
}
} catch (InputMismatchException e) {
System.out.println("Incorrect data");
course.setId(0);
}
System.out
.println("==================================================================================");
}
public void SeminarId(Course course) {
{
file=new File("Files1/seminar.txt");
FileReader i =new FileReader(file);
BufferedReader in = new BufferedReader(i);
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
System.out.println("==================================================================================");
}
}
}
I want to print everything inside seminar.txt file but unable to do it.Its done inside SeminarId function.It asks to put a try catch when pointing in filereader and readLine and in.close.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
public Course inputCourse() {
System.out.println("======inputing the course======");
//file = new File("Files1/Courses.txt");
//Creating a Scanner object
//Scanner sc = new Scanner(file);
scanner= new Scanner(System.in);
Course course = new Course();
CourseId(course);
CourseName(course);
Coursefee(course);
//Course path = new Course();
Seminar("Files1/seminar.txt");
return course;
}
public Course inputCourse() {
System.out.println("======inputing the course======");
//file = new File("Files1/Courses.txt");
//Creating a Scanner object
//Scanner sc = new Scanner(file);
scanner= new Scanner(System.in);
Course course = new Course();
CourseId(course);
CourseName(course);
Coursefee(course);
//Course path = new Course();
Seminar("Files1/seminar.txt");
return course;
}
public void Seminar(String path) {
{
try {
System.out.println("======Reading from the file======");
fr = new FileReader(path);
br = new BufferedReader(fr);
String s;
while ((s = br.readLine()) != null)
System.out.println(s);
fr.close();
} catch (IOException e) {
System.out.println("Exception: " + e);
e.printStackTrace();
} finally {
try {
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("==================================================================================");
}}
By doing this you can print all elements in seminar.txt
I am able to write data (serialize Object) into the file correctly but while reading the data I am only getting the first one. What is the problem in my code? I think I am deserializing object in correct way, because I checked it in some others code, they are also doing in the same way.
My files are like this :
Main.java
package com.company;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
int i =0;
int choice = 0;
ListIterator iterator;
Scanner sc = new Scanner(System.in);
LinkedList<Employee> employeeList = new LinkedList<Employee>();
LinkedList<Employee> employeeArrayList ;
File file = new File("./src/com/company/employeeInfo.txt");
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
ObjectInputStream objectInputStream = null;
FileInputStream fileInputStream = null;
Employee employee = new Employee();
while(true)
{
System.out.println("Main Menu");
System.out.println("1.Add an Employee");
System.out.println("2.Display All");
System.out.println("3.Exit");
choice = Integer.parseInt(sc.nextLine());
switch (choice)
{
case 1:
System.out.print("Enter Employee ID : ");
employee.id = Integer.parseInt(sc.nextLine());
System.out.println(" Enter Employee Name : ");
employee.name = sc.nextLine();
System.out.println("Enter Employee Age : ");
employee.age = Integer.parseInt(sc.nextLine());
System.out.println("Enter Employee Salary : ");
employee.salary = Double.parseDouble(sc.nextLine());
System.out.println(employeeList.add(employee));
try{
fileOutputStream = new FileOutputStream(file,true);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(employeeList);
objectOutputStream.close();
}
catch (IOException | NullPointerException exception)
{
System.out.println(exception.getMessage());
}
break;
case 2:
try {
System.out.println("----Report----");
// sc = new Scanner(file);
fileInputStream = new FileInputStream(file);
objectInputStream = new ObjectInputStream(fileInputStream);
employeeArrayList = (LinkedList<Employee>) objectInputStream.readObject();
iterator = employeeArrayList.listIterator();
System.out.println(employeeArrayList);
while (iterator.hasNext())
{
employee = (Employee) iterator.next();
System.out.println(employee.toString() );
}
}
catch (FileNotFoundException | NullPointerException e )
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
System.out.println(e.getMessage());
}
break;
case 3:
try
{
objectInputStream.close();
fileInputStream.close();
}
catch (IOException e)
{
System.out.println(e);
}
System.exit(0);
break;
}
}
}
}
Employee.java
package com.company;
import java.io.Serializable;
public class Employee implements Serializable {
int id;
String name;
int age ;
double salary;
public String toString() {
return id+" "+name +" "+age+" "+salary ;
}
}
The problem is that you are opening the file in "append" mode. This is controlled by the boolean true parameter you pass to FileOutputStream constructor:
fileOutputStream = new FileOutputStream(file,true);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
In the "append" mode, what you write to the file is added to the end of the file ("appended"). The existing contents of the file are not replaced, which is what you seem to want.
Solution: stop using the append mode. This will replace the old contents of the file with the new content you are writing.
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
I have an issue with the input I am getting from reading a file.
The file is made in another activity and is very simple:
ArrayList stuff = new ArrayList();
stuff.add("1,2,3");
try{
String saveFile = "saveGamesTest1.csv";
FileOutputStream saveGames = openFileOutput(saveFile, getApplicationContext().MODE_APPEND);
ObjectOutputStream save = new ObjectOutputStream(saveGames);
save.writeObject(stuff);
save.close(); }
In the other activity it's being read via
try {
FileInputStream fileIn=openFileInput("saveGamesTest1.csv");
InputStreamReader InputRead = new InputStreamReader(fileIn);
Scanner s = new Scanner(InputRead).useDelimiter(",");
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
}
I was expecting (and hoping) to get a result back like
1
2
3
However, the result I'm getting is this:
/storage/emulated/0/Android/data/ys.test/files/saveGamesTest1.csv����sr��java.util.ArrayListx����a���I��sizexp������w������t��1
2
3x
What am I doing wrong?
.
EDIT
I tried Serializable as suggested below, like follow:
public class Save implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
}
public void save(){
Save e = new Save();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try {
String saveFile = "save.ser";
FileOutputStream saveGames = openFileOutput(saveFile, getApplicationContext().MODE_APPEND);
ObjectOutputStream out = new ObjectOutputStream(saveGames);
out.writeObject(e);
out.close();
saveGames.close();
System.out.printf("Serialized data is saved in save.csv");
}
catch(IOException i) {
i.printStackTrace();
out.println("Save exception gepakt");
}
}
However, out.writeObject(e); gives an error saying that this isn't Serializable
You are not storing object as csv but as serialize java object you have to read as an object not as a csv file
take a look here https://www.tutorialspoint.com/java/java_serialization.htm
at Serializing an Object part
You have to use
FileInputStream in = null;
ObjectInputStream ois = null;
ArrayList stuff2 = null;
try {
in = openFileInput("saveGamesTest1.csv");
ois = new ObjectInputStream(in);
stuff2 = (ArrayList) ois.readObject();
} catch(IOException e) {...}
catch(ClassNotFoundException c) {...}
finally {
if (ois != null) {
ois.close();
}
if (in != null) {
in.close();
}
}
If you want a csv file you have to build it for instance by iterate over your array and write one by one the value in your file and adding the separator or follow this
How to serialize object to CSV file?
EDIT :
An elegant way in Java 7 to serialize an object (here a list like in your example) and deserialize :
public class Main {
public static void main(String[] args) {
List<Integer> lists = new ArrayList<>();
List<Integer> readList = null;
String filename = "save.dat";
lists.add(1);
lists.add(2);
lists.add(3);
//serialize
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
oos.writeObject(lists);
} catch (IOException e) {
e.printStackTrace();
}
//don't need to close because ObjectOutputStream implement AutoCloseable interface
//deserialize
try (ObjectInputStream oos = new ObjectInputStream(new FileInputStream(filename))) {
readList = (List<Integer>) oos.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
//don't need to close because ObjectInputStream implement AutoCloseable interface
//test
if(!lists.equals(readList)) {
System.err.println("error list saved is not the same as the one read");
}
}
}
How can I save an ArrayList to a file?
What am I doing wrong?
I have used this SO question to help me with Serializable objects.:
how to serialize ArrayList on android
and I used this SO question on how to write an array list:
Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?
However when I attempt to write the to the file I get the error:
java.io.NotSerializableException: at
java.io.ObjectOutputStream.writeObject at
com.mycompany.MyClass.saveData
Here is MyClass that attempts to save the file
private ArrayList < MyCustomObject > arrayList;
private File dataFile;
private String FILE_NAME = "FILE_DATA.dat";
public void init(final Context context) {
this.appContext = context;
dataFile = new File(appContext.getFilesDir(), FILE_NAME);
if (dataFile.exists()) {
loadData();
} else {
try {
dataFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
arrayList = new ArrayList < MyCustomObject > ();
saveData();
}
}
private void saveData() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dataFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fos != null) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(fos);
if (oos != null) {
oos.writeObject(arrayList);
}
assert oos != null;
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void loadData() {
FileInputStream fis = null;
try {
fis = new FileInputStream(dataFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fis != null) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(fis);
if (ois != null) {
try {
arrayList = (ArrayList < MyCustomObject > ) ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
}
assert ois != null;
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here is MyCustomObject
public class MyCustomObject implements Serializable {
public String myname = "";
public String someOtherItem = "";
public int aNumber = 0;
public MyCustomObject getCustomObject() {
return this;
}
}
Replace this method
public MyCustomObject MyCustomObject() {
return this;
}
in your MyCustomObject class and your code should work fine. Use something like
public MyCustomObject getMyCustomObject() {
return this;
}
Because the way you name your method is conflicting wit the default constructor that java creates for MyCustomObject class when you do not provide a constructor yourself. I assume that you are using this method to be able to add an instance of MyCustomObject to your array list: you don't really need such a method but with the proper naming you can still use it.
You should also put sample datas in your ArrayList before saving it to the disk by calling the saveData() method.
Here is an illustration from your code that works. I am not sure what your Context object is exactly but your are using it to get access to the file path, so to get things going I just used a particular file path.
public class MyClass {
private ArrayList < MyCustomObject > arrayList;
private File dataFile;
private String FILE_NAME = "FILE_DATA.dat";
public void init(final Context context) {
dataFile = new File("C:\\lompo\\file1.txt");
if (dataFile.exists()) {
loadData();
} else {
try {
dataFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
arrayList = new ArrayList < MyCustomObject > ();
MyCustomObject obj1 = new MyCustomObject();
obj1.aNumber = 125;
obj1.myname = "HIS NAME";
arrayList.add(obj1);
saveData();
}
}
public static void main(String[] args) {
MyClass myClazz = new MyClass();
myClazz.init(null);
System.out.println("Arraylist has " + myClazz.arrayList.size() + " elements");
}
private void saveData() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dataFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fos != null) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(fos);
if (oos != null) {
oos.writeObject(arrayList);
}
assert oos != null;
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void loadData() {
FileInputStream fis = null;
try {
fis = new FileInputStream(dataFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fis != null) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(fis);
if (ois != null) {
try {
arrayList = (ArrayList < MyCustomObject > ) ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
}
assert ois != null;
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
As you can see in the code, the first run of the main method will save the file on disk with an arrayList populated by one object. The second run reads from the file and then I printed the number of elements and the infos that I have saved before: the picture illustrates the result
I'm having an issue reading and loading objects to and from a BIN file i keep getting the errors "java.io.WriteAbortedException" and "java.io.NotSerializableException". This is even when my Student object implements Serializable...
LOADER:
try{
FileInputStream fis = new FileInputStream("students.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
while(true){
Student[] stu = null;
int i = 0;
try {
stu = (Student[]) ois.readObject();
studentBag.add(stu[i]);
} catch (EOFException e) {
break;
}
System.out.println(student);
i++;
}
SAVER:
Student[] studentArray = new Student[2];
studentArray[0] = student;
try {
FileOutputStream fos = new FileOutputStream("students.dat", true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(studentArray);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Nope");
}
Yes I did close the try catches just didnt see a point in putting them here.
Also im getting the errors at this line in the Loder stu = (Student[]) ois.readObject();
and this in the saver studentArray[0] = student;