Java之I/O流io和nio
I/O流
最近在学习java io 和java nio
提到io,我们常用的类和其作用如下图:
io的核心方法是read和write
以字节流为例:
1 package io; 2 3 import java.io.*; 4 import java.util.Arrays; 5 6 public class IO_Test { 7 8 private static byte[] bytes =null; 9 10 static int bytesum = 0; 11 12 public static void InputStreamTest() throws IOException { 13 14 /** 15 * File输入文件流的path必须是绝对路径 16 * this.getClass().getResourceAsStream("相对路径")返回的InputStream的实现 17 */ 18 File file = new File("D:\\IdeaProjects\\Test\\src\\io\\阿威十八式.txt"); 19 20 FileInputStream fis = null; 21 22 try { 23 fis = new FileInputStream(file); 24 25 bytes = new byte[40]; 26 27 for (int s = 0; s < 10; s++) { 28 /** 29 * '阿威十八式,全套不打折'utf-8编码文件 30 * read(byte[] bytes) 一次性读取bytes容量的字节数,返回的是已经读取的字节数 31 * 而read()方法一次只读一个字节数,并返回该字节。 32 */ 33 bytesum = fis.read(bytes); 34 //到读到文件结尾时,bytesum将返回-1, 35 System.out.println(bytesum); 36 if (bytesum < 0) { 37 return; 38 } 39 System.out.println(Arrays.toString(bytes)); 40 } 41 42 } catch (FileNotFoundException e) { 43 e.printStackTrace(); 44 } catch (IOException e) { 45 e.printStackTrace(); 46 } finally { 47 fis.close(); 48 } 49 } 50 51 public static void outputStreamTest(int length){ 52 53 File file =new File("D:\\IdeaProjects\\Test\\src\\io\\全套不打折.txt"); 54 55 FileOutputStream fos = null; 56 57 try { 58 fos = new FileOutputStream(file); 59 String str = new String(bytes,"utf-8"); 60 System.out.println(str); 61 String str2 = new String(bytes,"GBK"); 62 System.out.println(str2); 63 fos.write(bytes,0,33); 64 65 66 }catch (IOException e){ 67 e.printStackTrace(); 68 } 69 } 70 public static void main(String[] args) throws IOException { 71 InputStreamTest(); 72 outputStreamTest(bytesum); 73 } 74 }
执行结果:
33 [-23, -104, -65, -27, -88, -127, -27, -115, -127, -27, -123, -85, -27, -68, -113, -17, -68, -116, -27, -123, -88, -27, -91, -105, -28, -72, -115, -26, -119, -109, -26, -118, -104, 0, 0, 0, 0, 0, 0, 0] -1 阿威十八式,全套不打折 闃垮▉鍗佸叓寮忥紝鍏ㄥ涓嶆墦鎶�
utf-8的汉字几乎都是3个字节,而空格' '占一个字节32,null占一个字节0,回车一个字节13,换行一个字节10