IO转换流
转换流提供了字节流与字符流之间的转换
- 字节流中的数据都是字符时,转成字符流操作更高效。
- 很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。
- InputStreamReader:将一个字节的输入流转换为字符的输入流
解码:字节、字节数组 —->字符数组、字符串
OutputStreamWriter:将一个字符的输出流转换为字节的输出流
- 编码:字符数组、字符串 —-> 字节、字节数组
代码实现:
@Test
public void test2() throws Exception {
//1.造文件、造流
File file1 = new File("dbcp.txt");
File file2 = new File("dbcp_gbk.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
//第二个参数指明了字符集,具体使用哪个字符集,取决于文件保存时使用的字符集
InputStreamReader isr = new InputStreamReader(fis,"utf-8");
OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
//2.读写过程
char[] cbuf = new char[20];
int len;
while((len = isr.read(cbuf)) != -1){
osw.write(cbuf,0,len);
}
//3.关闭资源
isr.close();
osw.close();
}
对象流
对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。
(但其实,后面我们都是用json来做这件事情的)
- ObjectOutputStream:将内存中的对象变成存储中的文件、再通过网络传输出去
- ObjectInputStream:将存储中的文件反序列化成内存中的对象
序列化
@Test
public void testObjectOutputStream(){
ObjectOutputStream oos = null;
try {
//1.
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
//2.
oos.writeObject(new String("我爱北京天安门"));
oos.flush();//刷新操作
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos != null){
//3.
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
反序列化
@Test
public void testObjectInputStream(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object obj = ois.readObject();
String str = (String) obj;
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois != null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
当序列化的时候是一个对象时:
- ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
- transient:将不需要序列化的属性前添加关键字transient,序列化对象的时候,这个属性就不会被序列化。
NIO
NIO是java从1.4版本以后引入的新的IO API。
- NIO支持面向缓冲区的(IO是面向流的)、基于 通道的IO操作。
- NIO将以更加高效的方式、功能更强大进行文件的读写操作。
- Path替换原有的File类。