Java对文本文件的操作

一 代码

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值