Java学习day36-文件字符流

一、文件字符流

1.读取文件操作步骤:

  ①建立一个对象,将已存在的一个文件加载进流。

  FileReader fr = new FileReader("Test.txt");

  ②创建一个临时存放数据的数组。

  char[] ch = new char[1024];

  ③调用流对象的读取方法将流中的数据读入到数组中。

  fr.read(ch);

2.注意:(字节流同理)

  ①定义文件路径时,注意:可以用"/"或者"\\"。

  ②在写入一个文件时,如果目录下有同名文件将被覆盖。

  ③在读取文件时,必须保证该文件已经存在,否则会出现异常。

package day17;

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

public class Test2 {
    public static void main(String[] args){
//        Test2.testFileReader("D:/test/tt1.txt");
        
//        Test2.testFileWriter("hello world", "D:/test/tt5.txt");
        
        Test2.copyFile("D:/test/tt5.txt", "D:/test/cc/tt5.txt");
    }
    
    
    /**
     * 文件字符输入流FileReader
     * 在写入一个文件时,如果目录下有同名文件将被覆盖。
     * @param text
     * @param inPath
     * */
    public static void testFileReader(String inPath){
        try {
            FileReader fr = new FileReader(inPath);//创建文件字符输入流的对象
            
            char[] c = new char[20];//创建临时存数据的字符数组
            
            int len = 0;//定义一个输入流的读取长度
            
            while((len = fr.read(c)) != -1){
                System.out.println(new String(c,0,len));
            }
            
            fr.close();//关闭流
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
    /**
     * 文件字符输出流FileWriter
     * 在读取文件时,必须保证该文件已经存在,否则会出现异常。
     * @param text 输出的内容
     * @param OutPath 输出的文件
     * */
    public static void testFileWriter(String text,String outPath){
        try {
            FileWriter fw = new FileWriter(outPath);
            fw.write(text);//写到内存中
            fw.flush();//把内存的数据刷到硬盘
            fw.close();//关闭流            
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
    /**
     * 字符流完成拷贝文件,字符流只适合操作内容是字符的文件
     * @param inPath
     * @param OutPath 
     * */
    public static void copyFile(String inPath, String outPath){
        try {
            FileReader fr = new FileReader(inPath);
            FileWriter fw = new FileWriter(outPath);
            
            char[] c = new char[100];
            
            int len = 0;
            
            while((len= fr.read(c)) !=-1){//这是读取数据
                fw.write(c, 0, len);//写数据到内存
            }
            
            fw.flush();//刷到硬盘
            
            fw.close();
            fr.close();
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
}

猜你喜欢

转载自www.cnblogs.com/su-peng/p/12593314.html