Java字符流的对文件的操作(从文件中读写)

值得注意的是每次对文件操作后都要进行显示的关闭文件流,虽然在程序结束后会自动关闭,但是如果程序庞大的话会出现问题,不如养成一个好习惯,有流的地方就写一个显示的流关闭

import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;

/**
 * 学习Java中的字符输入、输出流
 * @author 彼岸夜微凉
 */

public class FileCharater {
    public static void main(String args[]){
        String contect = "彼岸夜微凉!";//用来往文件中写的字符串
        File file = new File("c:\\Users\\Desktop\\file\\OutputStream.txt");
        char in[] = contect.toCharArray();//将字符串转换为字符数组,因为 FileWriter(char [])
        try{

            //字符流的写入数据
            FileWriter writer = new FileWriter(file);
            writer.write(in);
            writer.close();//值得注意的是每次对文件操作后都要进行显示的关闭文件流

            //字符流的读出数据
            FileReader reader = new FileReader(file);
            char[] deposit = new char[100];
            int count = 0;
            while( reader.read(deposit) != -1 ){
                String string = new String(deposit,0,deposit.length);
                System.out.println(string);
                reader.close();//值得注意的是每次对文件操作后都要进行显示的关闭文件流

            }
            
        }catch(IOException e){
            e.printStackTrace();
        }

    }
}

猜你喜欢

转载自blog.csdn.net/qq_40990854/article/details/81082268