javaIO流中文件的拷貝和圖片的拷貝

 文件拷貝實例:

利用文件輸入輸出流編寫一個實現文件拷貝的程序, 源文件名和目標文件名通過控制檯輸入。

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();
			}
		}		
	}
}
發佈了127 篇原創文章 · 獲贊 61 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章