一、FileInputStream
FileInputStream可以按照字节的单位处理文件。
1 构造方法
2 方法
二、FileOutputStream
1 构造方法
FileOutputStream(File file) | 创建文件输出流以写入由指定的 File对象表示的文件。目标文件存在会覆盖原内容。 |
FileOutputStream(File file, boolean append) | append=true表示文件目标文件存在继续追加内容。 |
FileOutputStream(FileDescriptor fdObj) | 创建文件输出流以写入指定的文件描述符,表示与文件系统中实际文件的现有连接。 |
FileOutputStream(String name) | 创建文件输出流以指定的名称写入文件。 |
FileOutputStream(String name, boolean append) | 创建文件输出流以指定的名称写入文件。 append=true表示文件目标文件存在继续追加内容。 |
2 方法
三、实现文件拷贝
1 每次读取1个字节
@Test
@DisplayName("使用字节流,每次读取1个字节")
public void testFileInputStream() throws IOException {
String inputImgPath = "src/main/resources/static/test1.jpg";
String outputImgPathFor = "src/main/resources/static/test2.jpg";
File inputImgFile = new File(inputImgPath);
File outputImgFile = new File(outputImgPathFor);
int readData = 0;
try (InputStream is = new FileInputStream(inputImgFile);
OutputStream os = new FileOutputStream(outputImgFile)
) {
while ((readData = is.read()) != -1) {
os.write(readData);
}
} catch (IOException e) {
e.printStackTrace();
}
}
2 每次读取字节数组
@Test
@DisplayName("使用字节流,每次读取1024个字节")
public void testFileInputStreamWithByteArray() throws IOException {
String inputImgPath = "src/main/resources/static/test1.jpg";
String outputImgPathFor = "src/main/resources/static/test2.jpg";
File inputImgFile = new File(inputImgPath);
File outputImgFile = new File(outputImgPathFor);
int readLength = 0;
byte[] bytes = new byte[1024];
try (InputStream is = new FileInputStream(inputImgFile);
OutputStream os = new FileOutputStream(outputImgFile)
) {
while ((readLength = is.read(bytes)) != -1) {
os.write(bytes, 0, readLength);
}
} catch (IOException e) {
e.printStackTrace();
}
}