次の FileIOTest.java は「きちんと」書いたプログラムである。少しものものしい。
FileIOTest.java |
1 /* 2 * FileIOTest.java 3 */ 4 5 import java.io.BufferedReader; 6 import java.io.BufferedWriter; 7 import java.io.FileInputStream; 8 import java.io.FileOutputStream; 9 import java.io.InputStreamReader; 10 import java.io.OutputStreamWriter; 11 12 public class FileIOTest { 13 14 public static void main(String[] args) { 15 // TODO 自動生成されたメソッド・スタブ 16 try { 17 int a = 2, b = 3; 18 FileOutputStream out_s = new FileOutputStream("output.data"); 19 OutputStreamWriter out_w = new OutputStreamWriter(out_s); 20 BufferedWriter out_b = new BufferedWriter(out_w); 21 out_b.write("" + a + "\n"); 22 out_b.write("" + b + "\n"); 23 out_b.close(); 24 out_w.close(); 25 out_s.close(); 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } 29 30 try { 31 FileInputStream in_s = new FileInputStream("output.data"); 32 InputStreamReader in_r = new InputStreamReader(in_s); 33 BufferedReader in_b = new BufferedReader(in_r); 34 String str = in_b.readLine(); 35 int c, d; 36 c = Integer.parseInt(str); 37 str = in_b.readLine(); 38 d = Integer.parseInt(str); 39 System.out.println("" + c + "+" + d + "=" + (d+c)); 40 in_b.close(); 41 in_r.close(); 42 in_s.close(); 43 } catch (Exception e) { 44 e.printStackTrace(); 45 } 46 } 47 } |