Java I/O应用专题
[*]标准I/O重定向
public class TestSetInput {public static void main(String args[]){FileInputStream fis;try {fis = new FileInputStream("source.txt");System.setIn(fis);int avg = 0;int total = 0;int count = 0;int num = 0;int i;BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));String s = reader.readLine();while(null != s && !s.equals("over")){i = Integer.parseInt(s);num ++;total+=i;avg=total/num;System.out.println("num=" + num + "\ttotal=" + total + "\tavg=" + avg);s = reader.readLine();}} catch (Exception e) {e.printStackTrace();}}} 假定在当前路径下存在数据文件source.txt(文件中应每行为一个整数,这里没有考虑数据格式非法的情况)
source.txt:
2373119208285 程序运行结果:
num=1total=23avg=23num=2total=96avg=48num=3total=215avg=71num=4total=423avg=105num=5total=708avg=141
页:
[1]