FileWriter实现从一个文件中读取内容并写到另一个文件中

FileWriter和FileOutputStream都是向文件写内容,区别是前台一次写一个字符,后者一次写一个字节

package com.janson.day20180827;

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

public class TestFileWriter {
    public static void main(String[] args) {
        FileReader r = null;
        FileWriter w = null;
        int f = 0;
        int num = 0;
        try {
            r = new FileReader(System.getProperty("user.dir") + "/src/com/janson/day20180827/TestFileReader.java");
            w = new FileWriter("D:/javaExample/file/TestFileReader.txt");
            while ((f = r.read()) !=-1) {
                w.write(f);
                num ++;
            }
            w.flush();
            w.close();
            System.out.println("写入文件成功,共写入了" + num + "个字节");
        }catch (FileNotFoundException e1) {
            e1.printStackTrace();
            System.out.println("找不到相应文件");
            System.exit(-1);
        }catch (IOException e2) {
            e2.printStackTrace();
            System.out.println("写入文件失败");
            System.exit(-1);
        }

    }
}

 

import java.io.*;

public class TestFileWriter2 {
    public static void main(String[] args) throws Exception {
        FileReader fr = new FileReader("d:/java/io/TestFileWriter2.java");
        FileWriter fw = new FileWriter("d:/java/io/TestFileWriter2.bak");
        int b;
        while((b = fr.read()) != -1) {
            fw.write(b);
        }
        fr.close();
        fw.close();
    }
}

 

import java.io.*;
public class FileCopy {
  public static void main(String[] args) {
      int b = 0;
      FileReader in = null;
      FileWriter out = null;
      try {
        in = new FileReader("d:/share/java/HelloWorld.java");
        out = new FileWriter("d:/share/java/io/HW.java");
        while((b=in.read())!=-1){
          out.write(b);
        }
        out.close();
        in.close(); 
        
      } catch (FileNotFoundException e2) {
        System.out.println("找不到指定文件"); System.exit(-1);
      } catch (IOException e1) {
        System.out.println("文件复制错误"); System.exit(-1);
      }
      System.out.println("文件已复制");
  }
}

 

posted @ 2018-09-07 16:23  那心之所向  阅读(486)  评论(0编辑  收藏  举报