Java serialization and deserialization

I created a simple program that serializes the String input from cmd to a .ser file. Part of the requirement is that the program must be able to add a new input and read the new input plus the old input. But I get a StreamCorruptedException if I read after the second input.

here is my launch on CMD .. how can I solve this StreamCorruptedException and why is this happening? codes are given below.

C:\Users\MSI\Desktop\Codes For Java>java WriteFile cc.ser Enter text and press ^Z or ^D to end. hah haha hahaha try ^Z C:\Users\MSI\Desktop\Codes For Java>java WriteFile cc.ser Enter text and press ^Z or ^D to end. asd asd asd asd asd ^Z C:\Users\MSI\Desktop\Codes For Java>java ReadFile cc.ser 1: haha 2: haha 3: hahaha 4: hahaha The Error is : java.io.StreamCorruptedException: invalid type code: AC at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1375) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) at ReadFile.main(ReadFile.java:23) 

WriteFile.java:

  import java.io.*; public class WriteFile implements java.io.Serializable { public static void main(String args[]) { try { File myFile = new File(args[0]); BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream(myFile,true)); System.out.println("Enter text and press ^Z or ^D to end."); String str; while ((str = br.readLine()) != null) { oos.writeObject(str); } br.close(); oos.close(); } catch (IOException i) { i.printStackTrace(); } }} 

ReadFile.java:

 import java.io.*; public class ReadFile { public static void main(String args[]) { try { int ctr = 0; File myFile = new File(args[0]); ObjectInputStream OIS = new ObjectInputStream (new FileInputStream( myFile )); String str; while ((str = (String)OIS.readObject()) != null) { System.out.println(++ctr + ": " + str); } OIS.close(); } catch (EOFException ex) { System.out.println("\nEnd of File Reached "); } catch (ClassNotFoundException c) { System.out.println("The Error is : "); c.printStackTrace(); }catch (IOException i) { System.out.println("The Error is : "); i.printStackTrace(); } }} 
+4
source share
4 answers

This exception occurs whenever you try to create a new OutputStream object for an existing input stream / try to read even before something is written in this case, the control information that was read from the stream of objects violates the internal consistency checks.

Use one OOS and OIS for the life of the socket and do not use other threads in the socket.

You can also do the same with threads in the same program.

If you want to forget what you wrote, use ObjectOutputStream.reset ().

+1
source

I think this problem arises from the fact that you are trying to read before it is written.

0
source

I edited my code after reading some answer to this question Adding to ObjectOutputStream

 import java.io.*; public class WriteFile implements java.io.Serializable { public static void main(String args[]) { try { File myFile = new File(args[0]); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); if (myFile.exists()) { AppendingObjectOutputStream AOOS = new AppendingObjectOutputStream(new FileOutputStream(myFile,true)); System.out.println("Enter text and press ^Z or ^D to end."); String str; while ((str = br.readLine()) != null) { AOOS.writeObject(str); } br.close(); AOOS.flush(); } else { ObjectOutputStream OOS = new ObjectOutputStream(new FileOutputStream(myFile,true)); System.out.println("Enter text and press ^Z or ^D to end."); String str; while ((str = br.readLine()) != null) { OOS.writeObject(str); } br.close(); OOS.flush(); } } catch (IOException i) { i.printStackTrace(); } }} 

and adding a new class from the question above

 public class AppendingObjectOutputStream extends ObjectOutputStream { public AppendingObjectOutputStream(OutputStream out) { super(out); } @Override protected void writeStreamHeader() throws IOException { // do not write a header, but reset: // this line added after another question // showed a problem with the original reset(); }} 

any suggestion to improve the code? sorry just new to Java programming

here was my new CMD launch

Microsoft Windows [version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C: \ Users \ MSI> CMD 'cmd' is not recognized as an internal or external command, operating program or batch file.

 C:\Users\MSI\Desktop\Codes For Java>java WriteFile haha.ser Enter text and press ^Z or ^D to end. a b c d ^Z C:\Users\MSI\Desktop\Codes For Java>java WriteFile haha.ser Enter text and press ^Z or ^D to end. e f g ^Z C:\Users\MSI\Desktop\Codes For Java>java ReadFile haha.ser 1: a 2: b 3: c 4: d 5: e 6: f 7: g End of File Reached 

I did not modify the readfile.java file ... thanks for the answers = D

0
source

A few questions that should be understood before entering your code and fixing an encoding problem.

1) Why do you need to use ObjectInputStream and ObjectOutputStream? If you just read and write a line, it is better to use BufferedWriter and BufferedReader. We use OIS and OOS to read and write the object.

2) Your question has nothing to do with serialization and de-serialization. Please do a google search to find out how to properly serialize and de-serialize. In the code snippet:

 public class WriteFile implements java.io.Serializable // there is no meaning to implement the mark up interface here. 

In short, mark only java.io.Serializable on a POJO or data object.

3) When you enter ctrl-c or ctrl-z, a system interrupt signal is triggered, the entire system will stop abruptly, which will damage the data record.

I took a little time to write a complete working sample for you. Hope you can get sth from my sample.

ConsoleWriter

 /** * Write Console String to a file * When you type quit or save it will write to the file in one go. * * @author Seabook Chen * */ public class SimpleConsoleWriter { private static final String NEW_LINE = System.getProperty("line.separator"); public static void main(String[] args) { if (args == null || args.length == 0) { throw new RuntimeException("Please specify the file name!!!"); } String filepath = args[0]; Scanner in = new Scanner(System.in); System.out.println("Please input your comments ...."); System.out.println("Type quit to finish the input! Please type exact quit to quit!!!"); System.out.println("Type save to write to the file you specified. "); StringBuilder sb = new StringBuilder(); while(true) { String input = in.nextLine(); if ("quit".equalsIgnoreCase(input) || "save".equalsIgnoreCase(input)) { System.out.println("Thanks for using the program!!!"); System.out.println("Your input is stored in " + filepath); break; } sb.append(input); sb.append(NEW_LINE); } FileWriter fw = null; BufferedWriter bw = null; try { fw = new FileWriter(filepath, true); bw = new BufferedWriter(fw); bw.write(sb.toString(), 0, sb.toString().length()); bw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } } } 

SimpleConsoleReader

 /** * Read a file and output in the console * * @author Seabook Chen * */ public class SimpleConsoleReader { public static void main(String[] args) { if (args == null || args.length == 0) { throw new RuntimeException("Please specify the file name!!!"); } File file = new File(args[0]); FileReader fr = null; BufferedReader br = null; String nextLine = null; try { fr = new FileReader(file); br = new BufferedReader(fr); while((nextLine = br.readLine()) != null ) { System.out.println(nextLine); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } } 
-one
source

Source: https://habr.com/ru/post/1497913/


All Articles