前言
下面记录输入、输出流的一些使用方式。
1.InputStream
场景一
假如有一个Spring boot工程,需要读取resource目录下文件的内容。(这种读取文件的方式同时适用于windows和Linux)
ClassPathResource resource = new ClassPathResource("xxx.txt");
try (InputStream in = resource.getInputStream()) {
StringBuilder builder = new StringBuilder();
int len = 0;
byte[] b = new byte[1024];
while ((len = in.read(b)) != -1) {
builder.append(new String(b, 0, len));
}
System.out.println(builder.toString());
} catch (Exception e) {
e.printStackTrace();
}
2.FileInputStream
场景一
从D盘根目录下读取图片,然后将图片输出到E盘根目录下。
FileInputStream in = new FileInputStream("D:\\风景.jpg");
FileOutputStream out = new FileOutputStream("E:\\美丽的风景.jpg");
try {
int len = 0;
byte[] b = new byte[100];
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
}finally{
out.flush();
out.close();
in.close();
}