Java IO
在Java里,与IO相关的API主要分为两种:字节流处理与字符流处理。流的来源和目的地有很多,比如:文件,网络连接,内存等。这里主要介绍在IO以及NIO里的字节流操作。
IO 字节流
顾名思义,读入/写出的都是一个个字节(-128~127)的数字。各种具体实现的读入字节流class都继承于抽象类InputStream,写出字节流class都继承于抽象类OutputStream。
1. 最简单的文件写出/读入字节流::FileOutputStream/FileInputStream
import java.io.*;
public class JavaIO {
public static void main(String[] args) throws IOException {
String fileName = "/tmp/res1.txt";
try(OutputStream fos = new FileOutputStream(fileName)) {
fos.write("hello".getBytes());
}
try(InputStream fis = new FileInputStream(fileName)) {
byte[] res = new byte[fis.available()];
fis.read(res);
System.out.println("read from " + fileName + ":" + new String(res) + ", size:" + res.length);
}
}
}
结果:
read from /tmp/res1.txt:hello, size:5
我们尝试往文件里写入字符串“hello”,写入字节数是5字节。我们可以查看下文件内容:
cshen@cshen-mac _delta_log % cat /tmp/res1.txt
hello%
可以看到,文件里的内容是可阅读的,但是此类API提供的接口只能读入/写出字节,如果我想写入一个float还得转成byte吗?
2. 支持读入/写出Java所有基本类型数据的写出/读入字节流:DataOutputStream/DataInputStream
import java.io.*;
public class JavaIO {
public static void main(String[] args) throws IOException {
String fileName2 = "/tmp/res2.txt";
try(DataOutputStream dos = new DataOutputStream(new FileOutputStream(fileName2))) {
dos.writeFloat(11.29f);
dos.writeInt(1);
}
try(DataInputStream dis = new DataInputStream(new FileInputStream(fileName2))) {
int size = dis.available();
float f = dis.readFloat();
int i = dis.readInt();
System.out.println("read from " + fileName2 + ", float:" + f + ", int:" + i + ", size:" + size);
}
}
}
结果:
read from /tmp/res2.txt, float:11.29, int:1, size:8
查看文件内容:
cshen@cshen-mac _delta_log % cat /tmp/res2.txt
A4��%
可以看到,文件内容已经变为不可阅读了。存储为8字节,是因为float会转化为int写进,也占4字节。但是此类API只支持读写基本Java数据类型,如果我想写入一个java对象该怎么办呢?
3. 对象字节流:ObjectOutputStream/ObjectInputStream
import java.io.*;
public class JavaIO {
public static void main(String[] args) throws IOException, ClassNotFoundException {
String fileName3 = "/tmp/res3.txt";
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName3))) {
oos.writeObject(new Person("cshen", 26));
oos.writeObject(new Dog("hihi"));
}
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName3))) {
Object res = ois.readObject();
System.out.println(res);
Object res2 = ois.readObject();
System.out.println(res2);
}
}
}
class Person implements Serializable {
public Person(String name, int age) {
thi