MENU

FIleReader(Writer)

June 24, 2018 • Read: 2969 • Java阅读设置

FileReader

import java.io.*;
public class TestFileReader {
    public static void main(String[] args) {
        FileReader fr = null;
        int c = 0;
        try {
            fr = new FileReader("D:/test.txt");
            int ln = 0;
            while((c = fr.read()) != -1) {
                System.out.println((char)c);
            }
            fr.close();
        }catch(FileNotFoundException e) {
            System.out.println("找不到指定文件");
        } catch (IOException e) {
            System.out.println("文件读取错误");
        }
    }
}

FileWriter

import java.io.*;
public class TestFileWriter {
    public static void main(String[] args) {
        FileWriter fw = null;
        try {
            fw = new FileWriter("D:/test2.txt");//不存在就自动创建
            for(int i = 0;i < 50000;i++)
                fw.write(i);
            fw.close();
        }catch(IOException e) {
            e.printStackTrace();
            System.out.println("文件写入错误");
            System.exit(-1);
        }
    }
}

打开文件看到一些问号,并不是写入不成功,而是因为我们机器上没有该国家的语言配置,无法查看这种语言而已

Last Modified: October 19, 2018
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment