1 package com.copyfile; 2 /** 3 * 复制文档 4 * 5 */ 6 import java.io.FileInputStream; 7 import java.io.FileNotFoundException; 8 import java.io.FileOutputStream; 9 import java.io.IOException; 10 11 public class CopyFile { 12 public static void main(String[] args) { 13 FileInputStream fis = null;//创建一个输入流 14 FileOutputStream fos = null;//创建一个输出流 15 String str = ""; 16 try { 17 fis = new FileInputStream("D:/HelloWorld/Hello.java.txt"); 18 fos = new FileOutputStream("D:/HelloWorld/CopyFile.txt"); 19 //读取文件内容存入str 20 int temp = -1; 21 while((temp = fis.read())!=-1) {//读取完毕文件内容后的值为-1 22 str += (char)temp; 23 } 24 System.out.println("文档已读取完毕!"); 25 //将读取文件放在bytes数组中 26 byte[] bytes = str.getBytes(); 27 //复制读取到的文件 28 fos.write(bytes); 29 System.out.println("文档已复制"); 30 fos.flush(); 31 32 } catch (FileNotFoundException e) { 33 e.printStackTrace(); 34 } catch (IOException e) { 35 e.printStackTrace(); 36 } finally { 37 try { 38 fos.close(); 39 fis.close(); 40 } catch (IOException e) { 41 e.printStackTrace(); 42 } 43 44 } 45 } 46 }