提示
Java IO BufferedInputStream 使用示例。@ermo
# BufferedInputStream 使用示例
BufferedInputStream
是一个包装类,继承的父类是 FilterInputStream
。可以提供缓冲读取功能。
主要有2个构造器:
public BufferedInputStream(InputStream in)
public BufferedInputStream(InputStream in, int size)
默认的缓存数组大小是8196字节,可以通过第2个构造器进行自定义缓存数组大小。
看一个简单示例:
public static void readFile() throws IOException {
String filepath = "src/main/resources/order2.txt";
BufferedInputStream in = new BufferedInputStream(new FileInputStream(filepath));
byte[] bytes = new byte[1024];
int len;
while((len = in.read(bytes)) != -1) {
String data = new String(bytes, 0, len);
System.out.println(data);
}
in.close();
}
public static void main(String[] args) throws IOException {
readFile();
}
输出内容:
Some text for output file.
BufferedInputStream
也可以和其他装饰类进行组合使用。
下面的示例将读取 BufferedOutputStream
写入的 Order 数据。Order 类定义在 ,本文不再赘述。
public static List<Order> read() throws IOException {
String filepath = "src/main/resources/order1.txt";
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(filepath)));
try {
int size = in.readInt();
List<Order> orders = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
orders.add(new Order(in.readUTF(), in.readInt(), in.readDouble()));
}
return orders;
} finally {
in.close();
}
}
public static void main(String[] args) throws IOException {
List<Order> orders = read();
for (Order order : orders) {
System.out.println(order.toString());
}
}
执行程序,输出的内容如下:
Order{orderNo='123', orderType=1, orderAmount=10.5}
Order{orderNo='456', orderType=2, orderAmount=30.5}