java 字符流实现文件读写操作(FileReader-FileWriter)

时间:2022-03-09 21:39:38
java 字符流实现文件读写操作(FileReader-FileWriter)
备注:字符流效率高,但是没有字节流底层
字节流地址:http://pengyan5945.iteye.com/blog/1092120
Java代码  收藏代码
package com.frank.io;  
  
import java.io.BufferedReader;  
import java.io.File;  
import java.io.FileReader;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.io.Reader;  
import java.io.Writer;  
  
/**  
 * author:pengyan   
 * date:Jun 15, 2011   
 * file:WriterReaderTest.java  
 */   
public class WriterReaderTest {  
  
    File f=new File("E:\\abc.txt");  
      
    public static void main(String[] args) throws IOException{  
        WriterReaderTest test=new WriterReaderTest();  
        test.writeFile("Java字符流读写文件测试!");  
        test.readFile();  
    }  
    private void readFile()  throws IOException{  
        //reate BufferedReader with file    
        Reader r=new BufferedReader(new FileReader(f));  
        //in order to receive the value of this stream read every time    
        int temp=0;  
        //the all content of this stream read    
        String str="";  
        while ((temp=r.read())!=-1) {  
           //if not end,the total content add the value of the stream read this time    
            str+=(char)temp;  
        }  
        //show the content of the file  
        System.out.println("文件内容:"+str);  
    }  
    private void writeFile(String content) throws IOException {  
        if (f.exists()==false) {  
            f.createNewFile();//create file if not exist   
        }  
        //create FileWriter with file   
        Writer w=new FileWriter(f);  
        //write file  
        w.write(content);  
        //flush this stream    
        w.flush();  
        //close this stream    
        w.close();  
    }  
  
}