前言:
Java中流是重要的内容,基础的文件读写与拷贝知识点是很多面试的考点。故通过本文进行简单测试总结。
2.图展示【文本IO/二进制IO】(这是参考自网上的一张总结图,相当经典,方便对比记忆)
3.文本复制的实验Java实现code:
1 package com.gdufe.io; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.DataInputStream; 6 import java.io.DataOutputStream; 7 import java.io.FileInputStream; 8 import java.io.FileOutputStream; 9 import java.io.IOException; 10 import java.io.InputStream; 11 import java.io.OutputStream; 12 13 public class TestInputOutputStream { 14 15 // private final static String SOURCE="t.txt"; 16 // private final static String TARGET="tt.txt"; 17 // private final static String SOURCE="p.png"; 18 // private final static String TARGET="pp.png"; 19 private final static String SOURCE="D:\\Tool_Software\\mysql-installer-community-5.6.23.0.msi"; 20 private final static String TARGET="mysql-installer-community-5.6.23.0.msi"; 21 //D:\Tool_Software\Ryuyan.zip 22 23 24 public static void main(String[] args) { 25 // TestInputOutputStream.copy1(SOURCE, TARGET); 26 // TestInputOutputStream.copy2(SOURCE, TARGET); 27 TestInputOutputStream.copy3(SOURCE, TARGET); 28 System.out.println("--End---"); 29 } 30 31 public static void copy1(String src,String tar){ 32 33 InputStream input = null; 34 OutputStream output = null; 35 try{ 36 input = new FileInputStream(src); 37 output = new FileOutputStream(tar); 38 int r; 39 while((r=input.read())!=-1){ 40 output.write((byte)r); 41 } 42 }catch(Exception e){ 43 e.printStackTrace(); 44 }finally{ 45 try { 46 input.close(); 47 output.close(); 48 } catch (IOException e) { 49 e.printStackTrace(); 50 } 51 } 52 53 } 54 public static void copy2(String src,String tar){ 55 InputStream input = null; 56 OutputStream output = null; 57 try{ 58 input = new FileInputStream(src); 59 output = new FileOutputStream(tar); 60 int length=0; 61 byte []b = new byte[1024]; 62 while((length=input.read(b))!=-1){ 63 output.write(b,0,length); 64 } 65 }catch(Exception e){ 66 e.printStackTrace(); 67 }finally{ 68 try { 69 input.close(); 70 output.close(); 71 } catch (IOException e) { 72 e.printStackTrace(); 73 } 74 } 75 } 76 77 public static void copy3(String src,String tar){ 78 InputStream input = null; 79 OutputStream output = null; 80 try{ 81 input = new DataInputStream(new BufferedInputStream(new FileInputStream(src))); 82 output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tar))); 83 /***经过亲测,buffer缓冲流读取时确实更快一些****/ 84 85 int length=0; 86 byte []b = new byte[1024]; //先将stream读入字节数组 87 while((length=input.read(b))!=-1){ 88 output.write(b,0,length); 89 } 90 }catch(Exception e){ 91 e.printStackTrace(); 92 }finally{ 93 try { 94 input.close(); 95 output.close(); 96 } catch (IOException e) { 97 e.printStackTrace(); 98 } 99 } 100 } 101 }
(附:参考代码时注意准备好测试文件,不然出现异常“file can‘t be found”!
文件拷贝到Java工程的直接目录下,刷新project可查看!
)
时间: 2024-11-03 22:40:43