Java控制台程序默认是以控制台键盘和显示器作为标准输入/输出设备,在有些情况下,我们可能希望将程序的标准输入/输出进行重定向,例如程序测试时可能需要大量的数据,如果使用控制台输入测试数据的话每次都要重新输入,这样会很烦琐,此时可以考虑进行输入重定向。
实例:将java标准输入流重定向到输入流,该输入流从磁盘读取文件作为输入内容。
数据文件内容如下(dataSysIn.txt):
10 20 30 40 50 60 70 80 90 end
代码如下:
package io.stream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class InputSetTest { public static void main(String[] args) { FileInputStream input = null; BufferedReader reader = null; try { input = new FileInputStream(new File("document/dataSysIn.txt")); // 标准输入流重定向到文件输入流 System.setIn(input); // 统计变量 int total = 0, avg = 0, count = 0; // 从标准输入流获取数据 reader = new BufferedReader(new InputStreamReader(System.in)); String line = reader.readLine(); while ( null != line && !"end".equals(line) ) { int temp = Integer.parseInt(line); count ++; total += temp; line = reader.readLine(); } avg = total / count; System.out.println("total=" + total + " avg=" + avg); } catch(Exception e) { e.printStackTrace(); } finally { if ( null != input ) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } if ( null != reader ) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
输出结果:
total=450 avg=50