a- package demo.io;
- import java.io.File;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- public class IODemo2 {
- /**
- * 复制文件到
- */
- public static void main(String[] args) {
- File srcFile = new File("c:\\Java review", "Test7.java");
- FileReader fr = null;
- FileWriter fw = null;
- try {
- fr = new FileReader(srcFile);
- fw = new FileWriter("Copy_1" + srcFile.getName());
- // copyByChar(fr, fw);
- copyByCharBuffer(fr, fw);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (fr != null)
- try {
- fr.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (null != fw)
- try {
- fw.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- private static void copyByCharBuffer(FileReader fr, FileWriter fw)
- throws IOException {
- char[] cbuf = new char[1024];
- int len = 0;
- while((len = fr.read(cbuf))!=-1){
- fw.write(cbuf,0,len);
- }
- fw.flush();
- System.out.println("done");
- }
- private static void copyByChar(FileReader fr, FileWriter fw)
- throws IOException {
- int ch = 0;
- while ((ch = fr.read()) != -1) {
- fw.append((char) ch);
- // fw.write((char)ch);
- }
- fw.flush();
- System.out.println("done");
- }
- }
复制代码
|
|