JavaIO流-FileInputStream、FileOutputStream位元組流
阿新 • • 發佈:2020-07-29
import org.junit.Test; import java.io.*; /** *InputStream/OutputStream * * 1.造檔案 * 2.造流 * 3.流讀寫 * 4.關閉流 * * FileInputStream不能讀取文字檔案 * * 結論: * 1.對於文字檔案,使用字元流處理(txt,java,c,cpp) * 2.對於非文字檔案,使用位元組流(mp4,mp3,avi,jpg,doc,ppt) * * * @author orz */ public class FileInputOutputStreamTest { @Testpublic void test1() { FileInputStream fis=null; FileOutputStream fos=null; try { File file1=new File("hello.txt"); File file2=new File("hi.txt"); fis=new FileInputStream(file1); fos=new FileOutputStream(file2);byte [] buffer=new byte[5]; int len; while ((len=fis.read(buffer))!=-1) { // String str=new String(buffer,0,len); // System.out.print(str); fos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); }finally { try { if(fos!=null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } try { if(fis!=null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 圖片複製 */ @Test public void test2() { FileInputStream fis=null; FileOutputStream fos=null; try { File file1=new File("picture1.png"); File file2=new File("picture2.png"); fis=new FileInputStream(file1); fos=new FileOutputStream(file2); byte [] buffer=new byte[5]; int len; while ((len=fis.read(buffer))!=-1) { fos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if(fos!=null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } try { if(fis!=null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * * 實現檔案複製 */ public void copyFileWithInputOutputStream(String srcPath,String destPath) { FileInputStream fis=null; FileOutputStream fos=null; try { File file1=new File(srcPath); File file2=new File(destPath); fis=new FileInputStream(file1); fos=new FileOutputStream(file2); byte [] buffer=new byte[1024]; int len; while ((len=fis.read(buffer))!=-1) { fos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if(fos!=null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } try { if(fis!=null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 檔案複製速度測試 */ @Test public void copyTest() { String srcPath="E:\\1.mp4"; String destPath="E:\\3.mp4"; long start=System.currentTimeMillis(); copyFileWithInputOutputStream(srcPath,destPath); long end=System.currentTimeMillis(); System.out.println("複製花費操作時間為"+(end-start));//1547 } }