文件读写并处理FileNotFoundException异常

本文介绍了如何在Java中进行文件读写操作,并处理FileNotFoundException异常,包括读取和写入文件的基本步骤及错误处理。
package lianxi;
 
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;
/**
 * 读写文件,处理FileNotFoundException异常
 * @author xiaoyu
 *
 */
public class ReadWriterFile {
    public static void main(String[] args)throws Exception {
        ReadWriterFile rwf = new ReadWriterFile();
        rwf.readFile();
        rwf.writeFile();
    }
    public void readFile()throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要读取的文件名:");
        String name = scanner.nextLine();
        BufferedReader br = null;
        while(br == null) {
            try {
                br = new BufferedReader(
                        new InputStreamReader(
                                new FileInputStream(name)));
            } catch (FileNotFoundException e) {
                System.out.println(br);
                System.out.println("读取文件错误,请重新输入:");
                name = scanner.nextLine();
            }  
        }
        System.out.println("读取文件成功!");
        while(true) {
                String line = br.readLine();
                if(line == null) {
                    break;
                }
                System.out.println(line);
        }
        br.close();
    }
     
    public void writeFile()throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入文件名:");
        PrintWriter pw = null;
        String name;
        while(pw == null) {
            try {
                name = scanner.nextLine();
                pw = new PrintWriter(
                        new OutputStreamWriter(
                                new FileOutputStream(name,true)));
                //true表示追加,没有表示覆盖原文件!
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("文件格式错误,请重新输入:");
                name = scanner.nextLine();
                pw = null;
            }
        }
        System.out.println("创建或读取文件成功!");
        pw.write("don't worry,");
        pw.write("be happy!");
        pw.flush();
        pw.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值