I/O流分类
(1)按数据流的流向不同分为:输入流,输出流
输入/输出是相对于java应用程序即内存而言:
从文件等 → java程序内存:输入流。
从java程序内容 → 文件等:输出流。
(2)按操作数据单位不同分为:
字节流:按字节,8 bit,适合二进制文件)
字符流:按字符,每个字符多少字节与编码格式有关,适合文本文件
最顶端的抽象基类:
输入流:字节流-InputStream,字符流-Reader
输出流:字节流-OutputStream,字符流-Writer
(3)按流的角色不同分为:
节点流(与数据源如文件、网络、java内存等直接关联的流),
处理流/包装流(使用到设计模式:装饰器模式)
Java IO流的写法
JAVA7之前的写法try-catch-finally
在try-catch-finally块外声明变量并初始化为null,try块内初始化、读写流,在finally块中关闭流声明输入输出流变量
try {
// 初始化流
// 流读写
} catch (Exception e) {
// 异常处理
} finally {
// 关闭流
}
文件复制示例:将一个文件中的内容复制到另一个文件中,并使用缓存流提高读写效率。
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
fileInputStream = new FileInputStream("D:\\test.txt");
bufferedInputStream = new BufferedInputStream(fileInputStream);
fileOutputStream = new FileOutputStream("D:\\test1.txt");
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
int readLength = 0;
byte[] buffer = new byte[1024];
while ((readLength = bufferedInputStream.read(buffer)) != -1) {
//不能直接使用write(buffer)
bufferedOutputStream.write(buffer, 0, readLength);
}
// flush方法是否调用均可,很多输出流的close方法中也会调用flush方法
bufferedOutputStream.flush();
} catch (Exception e) {
// 异常处理
e.printStackTrace();
} finally {
// 关闭流,流的close方法需要try-catch,不然一个流关闭失败可能会影响剩下流的关闭,一般关闭时的异常不做特殊处理
if(bufferedInputStream != null) {
try {
bufferedInputStream.close();
} catch (IOException e) {
// 异常处理
e.printStackTrace();
}
}
if(bufferedOutputStream != null) {
try {
bufferedOutputStream.close();
} catch (IOException e) {
// 异常处理
e.printStackTrace();
}
}
}
JAVA7后新增的try-with-resource写法
在try块中定义输入输出流对象,则会在流的读写操作结束之后由系统自动关闭流
try(输入输出流定义) {
// 流读写
} catch (Exeception e) {
// 异常处理
}
上述文件复制示例重写:
try(FileInputStream fileInputStream = new FileInputStream("D:\\test.txt");
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream("D:\\test1.txt");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream)) {
int readLength = 0;
byte[] buffer = new byte[1024];
while ((readLength = bufferedInputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, readLength);
}
bufferedOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
看完之后是不是感觉代码少了很多,技术在升级,也在简化实现步骤。一起卷起来,学起来。