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
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
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(); } } } } }
source share