文件字符流输入

读取文件操作步骤:

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

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

  2. 创建一个临时存放数据的数组

    char[] ch = new char[1024]

  3. 调用流对象的读取 方法将流中的数据读入到数据中

    fr.read(ch);

public class demo06 {

public static void main(String[] args) {

    fileReader("D:\\test\\a\\tt1.txt");

    fileWriter("hello world","D:\\test\\a\\tt2.txt");

    //在写入一个文件是,如果目录下有同名文件将被覆盖
    copyFile("D:\\test\\a\\tt2.txt","D:\\test\\a\\tt3.txt");

}


/**
 * 文件字符输入流FileReader
 * @param inPath
 */
public static void fileReader(String inPath) {
    try {
        // 创建文件字符输入流对象
        FileReader fr = new FileReader(inPath);
        // 创建临时存数据的字符数组
        char[] c = new char[10];
        // 定义一个输入流的读取长度
        int len = 0;
        while((len = fr.read(c)) != -1) {
            String st = new String(c,0,len);
            System.out.println(st);
        }
        fr.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 文件字符输出流,把内容输出到指定的路径
 * @param text 输出的内容
 * @param outPath 输出的文件路径
 */
public static void fileWriter(String text,String outPath){
    try {
        FileWriter fw = new FileWriter(outPath);
        //把内容存储在内存中
        fw.write(text);
        //把内存的数据刷到硬盘中
        fw.flush();
        fw.close();
    } catch (Exception e) {
        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[10];
        int len = 0;
        //读取数据
        while((len = fr.read(c)) != -1){
            //写入数据进内存
            fw.write(c,0,len);
        }
        fw.flush();
        fr.close();
        fw.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

`