//創建一個copy 文件的方法
public static void copyfile(File src,File docfile)throws Exception{ //創建一個文件輸入流 FileInputStream input = new FileInputStream(src); //創建一個文件輸出流 FileOutputStream out =new FileOutputStream(docfile); //方法一str //定義一個變量接受讀取到的字節 /* int b = -1; while ((b=input.read())!=-1){ //System.err.println((char) b); // 把b接受的字符轉成char 其實打印的就是計算機編碼 //把讀到的字節寫入到目標文件 out.write(b); }*/ //方法一end 方法二str 如果文件較大也可以設置緩沖區 如下; /* *下面是設置了緩存區 相比上邊方法效率要高很多 * 相比上邊的方法有點像喝水 每次一滴一滴喝 不太過癮 加緩存區好比是那杯子接滿了 一下喝完 杯子就是我們下邊聲明的數組; * **/ //定義一個用來緩沖的數組 就是每次讀到的字節先放到緩存區然后一並輸出提高效率; byte[] b = new byte[1024]; //用來接收每次讀到的字節數量; int len = -1; //read(byte[]) 讀取一定數量的字節也就是參數設置的大小 放到緩存區 返回每次讀取的字節數量 read() 返回每次讀取到的字節; while ((len=input.read(b))!=-1){ //將緩存區的字節輸出到目標文件 因為文件末尾讀到的字節數不確定所以 每次輸出緩存區的 0 到 實際讀到的字節長度; out.write(b,0,len); } //因為輸入出流用到系統級資源 所以要關流釋放資源; input.close(); out.close(); }
public static void main(String[] sage){ //要復制的 源文件 File file =new File("E:\\加班記錄.txt"); //目標文件路徑 String filePath="E:\\copy\\copy2\\copy3"; File docParent= new File(filePath); //判斷當前文件或文件夾是否存在; if(!docParent.exists()){ //如果路徑目錄不存在創建文件目錄 docParent.mkdirs(); //值創建子目錄 如:創建copy3目錄 copy2 必須存在否則不創建 mkdirs()是創建所有目錄; // docParent.mkdir(); } //創建一個目標文件; File docFile =new File(filePath+File.separator+"copy加班記錄.txt"); try { //執行copy方法; copyfile(file,docFile); } catch (Exception e) { e.printStackTrace(); } }