文件拷貝實例:
利用文件輸入輸出流編寫一個實現文件拷貝的程序, 源文件名和目標文件名通過控制檯輸入。
public class Copy {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入您要拷貝的源文件:");
String str = sc.next();
System.out.print("請輸入您要拷貝的目標文件:");
String s = sc.next();
/*
* 方法一:
* try {
FileInputStream fis = new FileInputStream(str);
byte[] b=new byte[fis.available()];
fis.read(b);
System.out.println("源文件內容:");
System.out.println(new String(b));
fis.close();
try {
FileOutputStream fos = new FileOutputStream(s);
String st = new String(b);
fos.write(st.getBytes());
fos.flush();
fos.close();
System.out.println("文件拷貝成功!");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
System.out.println("源文件未找到!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//方法二:
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(str);
fos = new FileOutputStream(s);
byte[] b = new byte[fis.available()];
while (fis.read(b)!=-1) {
fos.write(b);
}
System.out.println("文件拷貝成功!");
} catch (FileNotFoundException e) {
System.out.println("源文件未找到!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(fis != null){
fis.close();
}
if(fos != null){
fos.flush();
fos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
圖片拷貝實例:
將圖片根據原路徑拷貝到另一個路徑內
public class PictureCopy {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("E:/iodemo/99.jpg");
fos = new FileOutputStream("E:/iodemo/00.jpg");
byte [] b = new byte[fis.available()];
while (fis.read(b)!=-1) {
fos.write(b);
}
fos.close();
System.out.println("圖片拷貝成功!");
} catch (FileNotFoundException e) {
System.out.println("源文件未找到!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//finally關鍵字:無論出不出現異常最後都要執行finally語句中的代碼
//最後再關閉流
try {
if(fis!=null){
fis.close();
}
if(fos != null){
fos.flush();
fos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}