fork download
  1. import java.io.Serializable;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.ObjectInputStream;
  5. import java.io.ObjectOutputStream;
  6.  
  7. /**
  8.  * アプリ設定クラス
  9.  */
  10. class AppOption implements Serializable{
  11.  
  12. private static final long serialVersionUID = 5245782620871594321L;
  13.  
  14. private String option;
  15.  
  16. public String getOption() {
  17. return option;
  18. }
  19.  
  20. public void setOption(String option) {
  21. this.option = option;
  22. }
  23.  
  24. }
  25.  
  26.  
  27. /**
  28.  * IO処理
  29.  */
  30. public class Main {
  31.  
  32. public static void main(String[] args) {
  33. fwrite();
  34. fread();
  35. }
  36.  
  37. public static void fwrite() {
  38.  
  39. AppOption appOption = new AppOption();
  40.  
  41. // フィールドに値を設定
  42. appOption.setOption("OptionValue");
  43.  
  44. try (FileOutputStream fos = new FileOutputStream("./setting");
  45.  
  46. // フィールドの値ごとファイルに書き込む
  47. oos.writeObject(appOption);
  48.  
  49. } catch (Exception e) {
  50. System.err.println(e);
  51. }
  52. }
  53.  
  54. public static void fread() {
  55. try (FileInputStream fis = new FileInputStream("./setting");
  56.  
  57. // ファイルに書き込まれたインスタンスを読み込む
  58. AppOption appOption = (AppOption) ois.readObject();
  59.  
  60. // デバッグ用表示 -> OptionValue
  61. System.out.println(appOption.getOption());
  62.  
  63. } catch (Exception e) {
  64. System.err.println(e);
  65. }
  66. }
  67. }
Success #stdin #stdout #stderr 0.1s 320512KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
java.io.FileNotFoundException: ./setting (Permission denied)
java.io.FileNotFoundException: ./setting (No such file or directory)