IO 章节 学习-InputStream & OutputStream
1 import java.io.*; 2 3 /** 4 * Created by wojia on 2017/7/6. 5 */ 6 public class fileCopyDemo { 7 /**实验 如何copy一个文本文档到副本中 8 * 这里使用了java7的新特性 try(){}catch 进行自动关闭资源 9 * */ 10 public static void main(String args[]) { 11 //length用于接收read的return 12 int length = -1; 13 //1.指定source-file-path 14 File srcfile = new File( "E:/test/test.txt" ); 15 //1.指定dest-file-path 16 File destfile = new File( "E:/test/test_copy.txt" ); 17 //create temp array[1024],one byte 18 byte[] buffer = new byte[1024]; 19 byte[] buffer2 = new byte[1024]; 20 21 try ( 22 //2.create an inputstream 23 InputStream in = new FileInputStream( srcfile ); 24 //2. create an output stream 25 OutputStream out = new FileOutputStream( destfile ) 26 ) 27 { /*copy(read) the byte content from srcfile*/ 28 /**in.read: 29 * when the input stream is empty, return -1,else return the length of byte[] 30 * */ 31 while((length = in.read( buffer ))!= -1){ 32 /** 33 * note : new String(byte[],int off ,length) 是把byte[] 转成 String的最好方式 34 * 而 <String(instance).toString></String(instance).toString> 是string 转 byte[] 的方法,例如 "abc".toString / "abc".toByteChar() 35 * */ 36 System.out.println(new String(buffer,0,length)); 37 } 38 // output the byte[] to the destination file 39 out.write( buffer ); 40 //input what we output 41 InputStream in2 = new FileInputStream( destfile ); 42 in2.read( buffer2 ); 43 //print it out ,buffer2 is the same as buffer1 44 System.out.println(new String(buffer2)); 45 } catch (IOException e) { 46 e.printStackTrace(); 47 48 49 } 50 } 51 }
2017-07-07更新:
the deifference between Arrays.toString(byte[] buffer) and new String(byte[] buffer)
arrays的tostring是直接输出原ascii码的,就int类型
而String(byte[] buffer , charset) 是已经带了自动字节转码字符的了 若不指定charset 则默认 系统值