Java實現檔案拷貝(位元組流)
阿新 • • 發佈:2019-02-12
/**
* 拷貝檔案示例(位元組流)
*/
package JavaIO;
import java.io.*;
/**
* @author 16026
*
*/
public class CopyPicture {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
copy();
}
public static void copy(){
//建立位元組輸入輸出流
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("E:\\薛之謙 - 認真的雪.mp3"); //所要讀取的檔案地址
fos = new FileOutputStream("E:\\認真的雪.mp3"); //所要寫入的檔案地址
int num = 0;
byte [] by = new byte[1024];
while ((num = fis.read(by)) != -1){ //讀取檔案
fos.write(by, 0, num); //寫入檔案
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{ //關閉資源
if(fis != null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}