欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

文件读写并处理FileNotFoundException异常,,package lian

来源: javaer 分享于  点击 23036 次 点评:79

文件读写并处理FileNotFoundException异常,,package lian


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();    }}//该片段来自于http://byrx.net
相关栏目:

用户点评