一 代码
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class InputOutputDemo
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.print("输入文件名为: ");
String inputFileName = console.next();
System.out.print("输出文件名为: ");
String outputFileName = console.next();
// 创建Scanner对象和PrintWriter用以处理输入数据流和输出数据流
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile); // 把文件作为数据输入源,这里必须是File类
PrintWriter out = new PrintWriter(outputFileName); // 将数据输出到文件方法,这里可以是文件名
int count = 0;
double value;
double total = 0.0;
while (in.hasNextDouble())
{
value = in.nextDouble(); // 使用Scanner的方法进行读操作
out.printf("%6.2f\r\n", value);
total = total + value;
count++ ;
}
out.printf("总和为 : %8.2f\r\n", total);
out.printf("均值为 : %8.2f\r\n", total / count);
in.close(); // 关闭对象
out.close();// 关闭对象
}
}
二 运行
E:\Java\Java编程技术大全\范例源码、实战练习答案、赠送资源\范例源码\chap16\范例16-2>java InputOutputDemo
输入文件名为: input.txt
输出文件名为: output.txt
三 文件输出
32.20
54.10
67.50
29.80
35.00
90.00
117.20
44.50
101.20
65.50
102.60
66.78
33.45
25.89
总和为 : 865.72
均值为 : 61.84