Java代码复制文件
直接上代码
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class TestPrint26 { public static void main(String[] args) { String file1 = "D:\\ING\\172-26-223-soapui-project.xml"; //被复制的文件 String path = "C:\\ING"; //新文件路径 String file2 = "newfile.xml"; //新文件名 copyFile(file1, path, file2); } /** * 把file1复制到file2 * @param file1 要被复制的文件 * @param path 新文件所在目录 * @param file2 复制之后的新文件 */ public static void copyFile(String file1, String path, String file2) { FileInputStream fis = null; FileOutputStream fos = null; try { //新建file2的目录 File fileDir = new File(path); if (!fileDir.exists()) { fileDir.mkdirs(); } //新建file2 File newFile = new File(path + "\\" + file2); //新建两个流 fis = new FileInputStream(file1); fos = new FileOutputStream(newFile); byte[] buf = new byte[1024]; //可以写1024的倍数 int len = 0; while ((len = fis.read(buf)) != (-1)) { fos.write(buf, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); //关闭流 } } catch (IOException e2) { e2.printStackTrace(); } try { if (fos != null) { fos.close(); //关闭流 } } catch (IOException e2) { e2.printStackTrace(); } } } }