JavaIO流-FileInputStream、FileOutputStream字节流
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 { @Test public 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 } }