结果: (注意:我的D盘下没有那个文本文件)
出错时间: Fri Sep 02 11:33:05 CST 2011
错误信息:
java.io.FileNotFoundException: D:a.txt (系统找不到指定的文件。)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at java.io.FileReader.<init>(FileReader.java:41)
at v512.chap14.TestCharArrayWriter.main(TestCharArrayWriter.java:8)
6. I/O应用专题
①标准I/O重定向
例:标准输入重定向
package v512.chap14; import java.io.*; public class TestSetInput{ public static void main(String[] args){ try{ FileInputStream fis = new FileInputStream("D:\\source.txt"); System.setIn(fis); int avg = 0; int total = 0; int count = 0; int num = 0; int i; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); while(s != null && !s.equals("") && !s.equals("over")){ i = Integer.parseInt(s); num++; total += i; avg = total/num; System.out.println("num=" + num + "ttotal=" + total + "tavg=" + avg); s = br.readLine(); } }catch(Exception e){ e.printStackTrace(); } } }
source.txt 内容就是一些数字:
23
50
46
89
77
输出结果:
num=1 total=23 avg=23 num=2 total=73 avg=36 num=3 total=119 avg=39 num=4 total=208 avg=52 num=5 total=285 avg=57
例: 标准输出/标准错误输出重定向
package v512.chap14; import java.io.*; import java.util.Date; public class TestSetOutput{ public static void main(String[] args){ PrintStream ps = null; PrintStream ps_error = null; try{ FileInputStream fis = new FileInputStream("D:\\source.txt"); System.setIn(fis); ps = new PrintStream(new FileOutputStream("D:\\output.txt",true)); System.setOut(ps);//设置标准输出 ps_error = new PrintStream(new FileOutputStream("D:\\errorLog.txt",true)); System.setErr(ps_error);//设置标准错误输出 int avg = 0; int total = 0; int num = 0; int i; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); while(s != null && !s.equals("over")){ i = Integer.parseInt(s); num++; total += i; avg = total/num; System.out.println("num=" + num + "ttotal=" + total + "tavg=" + avg); s = br.readLine(); } }catch(Exception e){ System.err.println("出错时间: " + new Date()); System.err.print("错误信息:"); e.printStackTrace(System.err); }finally{ try{ ps.close(); ps_error.close(); }catch(Exception e1){ System.err.println("出错时间: " + new Date()); System.err.print("错误信息:"); e1.printStackTrace(System.err); } } } }
程序的得到的结果是:
输出文件内容:
num=1 total=23 avg=23 num=2 total=73 avg=36 num=3 total=119 avg=39 num=4 total=208 avg=52 num=5 total=285 avg=57
②属性信息导入/导出
例: 属性导出/导入
导出:
package v512.chap14; import java.io.*; import java.util.Properties; public class SaveProperties{ public static void main(String[] args){ try{ Properties ps = new Properties(); ps.setProperty("name","Scott"); ps.setProperty("password","Tiger"); FileWriter fw = new FileWriter("D:\\props.txt"); ps.store(fw,"loginfo"); fw.close(); }