java將一個文件復制到另一個文件夾


public static void main(String[] args) throws IOException {
//獲取要復制的文件
File oldfile=new File("D:\\IoTest\\aaa.txt");
//文件輸入流,用於讀取要復制的文件
FileInputStream fileInputStream = new FileInputStream(oldfile);
//要生成的新文件(指定路徑如果沒有則創建)
File newfile=new File("D:\\IoTest\\new\\aaa\\ccc.txt");
//獲取父目錄
File fileParent = newfile.getParentFile();
System.out.println(fileParent);
//判斷是否存在
if (!fileParent.exists()) {
// 創建父目錄文件夾
fileParent.mkdirs();
}
//判斷文件是否存在
if (!newfile.exists()) {
//創建文件
newfile.createNewFile();
}

//新文件輸出流
FileOutputStream fileOutputStream = new FileOutputStream (newfile);
byte[] buffer= new byte[1024];
int len;
//將文件流信息讀取文件緩存區,如果讀取結果不為-1就代表文件沒有讀取完畢,反之已經讀取完畢
while ((len=fileInputStream.read(buffer))!=-1) {
fileOutputStream.write(buffer, 0, len);
fileOutputStream.flush();
}
fileInputStream.close();
fileOutputStream.close();

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM