利用Java程式碼實現把一個檔案從一個地方剪下到另一個地方
阿新 • • 發佈:2019-02-12
1、實現原理:
通過輸入流讀取檔案的內容,在通過輸出流把讀取到的內容輸出到其他檔案中,然後再讀取結束後刪除原來的檔案就完成了檔案的剪下。
1)首先在將要把檔案剪下到的地方建立一個同一個型別的檔案;
2)利用輸入流讀取原檔案的內容;
3)在讀取的過程中,把讀取到的內容通過輸出流寫入到剛才建立的檔案中;
4)在檔案複製結束以後刪除原檔案既完成了檔案的剪下。
2、程式碼實現(把桌面的一個jpg檔案剪下到D盤中):
package copy; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class CutFileTest { public static void main(String[] args) { File file1 = new File("C:\\Users\\Administrator\\Desktop\\a.jpg"); File file2 = new File("D:\\a.jpg"); //在程式結束時刪除檔案1 file1.deleteOnExit(); try { //在D盤建立檔案2 file2.createNewFile(); } catch (IOException e) { e.printStackTrace(); } cutFile(file1, file2); } public static void cutFile(File file1, File file2){ FileOutputStream fileOutputStream = null; InputStream inputStream = null; byte[] bytes = new byte[1024]; int temp = 0; try { inputStream = new FileInputStream(file1); fileOutputStream = new FileOutputStream(file2); while((temp = inputStream.read(bytes)) != -1){ fileOutputStream.write(bytes, 0, temp); fileOutputStream.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); }finally{ if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }