现在的位置: 首页 > 综合 > 正文

第十八天:IO流

2018年05月16日 ⁄ 综合 ⁄ 共 2298字 ⁄ 字号 评论关闭

FileInputStream(File)
FileOutputStream(File)

FileInputStream(File file) 
          通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定。
FileInputStream(String name) 
          通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。\
          
//允许往这个文件里追加数据(如果不这样会覆盖这个文件)
OutputStream outputStream = new FileOutputStream(filename,true);

//左填充
private static String leftPad(
      String hex, char c, int size) {
    char[] cs = new char[size];
    //将指定的 byte  c 值分配给指定 byte 节型数组cs的每个元素。 
    Arrays.fill( cs, c);
    //hex.length()要复制的数组的长度
    System.arraycopy(hex.toCharArray(), 0, 
        cs, cs.length-hex.length(), hex.length());
    return new String(cs);
  }
  

BufferedInputStream(InputStream)
BufferedOutputStream(OutputStream)

ObjectInputStream(InputStream)
ObjectOutputStream(OutputStream)

/**
以前在使用流的时间,即要有什么字节 ,又要有编码,那么Reader就是从
字节到字符的跨越。

 * InputStreamReader 是字节流通向字符流的桥梁:它使用指定的 charset 
 * 读取字节并将其解码为字符。它使用的字符集可以由名称指定或显式给定,或者可以接受平台默认的字符集。 

每次调用 InputStreamReader 中的一个 read() 方法都会导致从底层输入流读取一个或多个字节。
要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节,使其超过满足当前读取操作所需的字节。 

为了达到最高效率,可要考虑在 BufferedReader 内包装 InputStreamReader。例如: 

 BufferedReader in
   = new BufferedReader(new InputStreamReader(System.in));
 
 *
 */
 
 字节流--》字符流--》缓冲区流   一层一层的包装。
 
InputStreamReader(InputStream)
OutputStreamWriter(OutputStream)

读取任何文本就用InputStreamReader(InputStream)这个是最常用的一个方法。
OutputStreamWriter outputStreamWriter2 = new 
OutputStreamWriter(new BufferedOutputStream(new FileOutputStream("gbk.txt",true)));

FileReader(File)
FileWriter(File)

BufferedReader(Reader)

PrintWriter(Writer)

文本编码:

GB2312是GBK的子集。

GBK: 1-2变长编码, 英文1字节与ascII一致, 中文2个Byte
中ABC: 
d6       d0       41       42       43
11010110 11010000 01000001 01000010 01000011 

GBK与UTF-8中没有任何对应关系 。

UTF-8: 1-4变长编码, 英文1字节与ascII一致, 中文3个Byte
中ABC:
e4       b8       ad       41       42       43 
11100100 10111000 10101101 01000001 01000010 01000011 

UTF-8中文编码: 1110xxxx 10xxxxxx 10xxxxxxx
xxxx为实际的Unicode编码, 其他为编码控制位

UTF-16BE: 2字节定长编码,中英文都采用固定长度表示.也是Java的内部编码, 
中ABC:
4e       2d       00       41       00       42       00       43 
01001110 00101101 00000000 01000001 00000000 01000010 00000000 01000011 

1) 二进制文件访问
   new BIS(new FIS(...))
   new BOS(new FOS(...)) 
2) 文本文件的访问
  new ISR(new FIS(...),"charset")
  new OSW(new FOS(...),"charset")
  new FR(...)
  new FW(...)
3)从控制台按行读取数据
 new BR(new ISR(System.in))
4)从文件按行读取数据
 new BR(new ISR(new FIS(...),"charset"))
 new BR(new FR(...))
5) 将各种类型数据以字符串形式输出到文件
 new PW(new OSW(new FOS(...),"charset"))
 new PW(new FW(...))
6) 对象序列化和反序列化
  new OOS(new FOS(...))
  new OIS (new FIS(...))

  

抱歉!评论已关闭.