import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Collection { public static void main(String[] args) throws FileNotFoundException, IOException{ File file = new File("D:/","copy1223.txt");//创建一个新的文件 InputStream input=new FileInputStream("D:/1223.txt");// 读入一个原有的文件 byte[] b=new byte[2048]; input.read(b); //把文件读到B中 input.close(); //必须关闭 OutputStream output=new FileOutputStream("D:/copy1223.txt"); output.write(b); //把B中的文件写入copy123中 output.close(); //必须关闭 } }
--------------------------------------------
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package testSet; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Administrator */ public class FileCopy { public static void main(String[] args){ File file = new File("D:/inst.exe"); File target = new File("D:/copy"+file.getName()); copyFile(file.getPath(),target.getPath()); } public static void copyFile(String file, String targetfile) { FileInputStream fis = null; FileOutputStream fos = null; File source = new File(file); if (!source.exists()) { System.err.println("File not exists!"); return; } try { fis = new FileInputStream(file); fos = new FileOutputStream(targetfile); byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) != -1) { fos.write(buffer, 0, len); fos.flush(); } } catch (FileNotFoundException ex) { Logger.getLogger(FileCopy.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(FileCopy.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } catch (IOException ex) { Logger.getLogger(FileCopy.class.getName()).log(Level.SEVERE, null, ex); } } } }