FileOutputStream类
文件字节输出流,⽤于内存向⽂件发送信息。
常用构造方法:
- FileOutputStream(String name) ; 创建输出流,先将文件清空,再不断写入。
- FileOutputStream(String name, boolean append) ; 创建输出流,若append为true,在原文件最后面以追加形式不断写入。
常用方法:
- write(int b) ; 写一个字节
- void write(byte[] b); 将字节数组中所有数据全部写出
- void write(byte[] b, int off, int len); 将字节数组的一部分写出
- void close() ; 关闭流
- void flush() ; 刷新
测试write()方法
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class FileOutputStreamTest01 {
public static void main(String[] args) {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream("C:\\Users\\dell\\Documents\\新建文件夹\\test.txt");
outputStream.write(97);
outputStream.write("\n".getBytes());
outputStream.write("hello".getBytes());
outputStream.write("world".getBytes());
outputStream.write("java".getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
文件的复制:使用FileInputStream和FileOutputStream完成
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileInputOutputStreamCopy {
public static void main(String[] args) {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
byte[] bs = new byte[1024];
try {
inputStream = new FileInputStream("C:\\Users\\dell\\Desktop\\books\\Java实践指南.pdf");
outputStream = new FileOutputStream("C:\\Users\\dell\\Documents\\新建文件夹\\Java实践指南.pdf",true);
int readCount = 0;
while((readCount = inputStream.read(bs))!=-1){
outputStream.write(bs);
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
if (inputStream!= null){
try {
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
使用try-with-resources语句
对于清理或关闭不再需要使用的资源 这种情况,处理资源的 try 语句(try-with-resources,TWR) 能自动关闭需要清理的资源。
try (InputStream is = new FileInputStream("/Users/ben/details.txt")) {
// ……处理这个文件
}
在TWR的资源子句中:
- 资源的作用域会自动放入try块中
- 声明资源时,只能声明实现了AutoCloseable接口的对象(这个接口表示资源自动关闭,编译器会插入自动异常处理代码)。
- 声明资源的数量不限。
import java.io.*;
public class TryWithResources {
public static void main(String[] args) {
try (
//以下声明的资源,InputStream、OutputStream,都实现了AutoCloseable接口
InputStream inputStream = new FileInputStream("C:\\Users\\dell\\Desktop\\books\\[图灵程序设计丛书].Java实践指南.pdf");
//可以声明多个资源
OutputStream outputStream = new FileOutputStream("C:\\Users\\dell\\Documents\\新建文件夹\\Java实践指南1.pdf",true)){
byte[] bytes = new byte[1024];
int readCount;
while ((readCount = inputStream.read(bytes))!=-1){
outputStream.write(bytes);
}
}catch (IOException e) {
//不再需要手动关闭资源
throw new RuntimeException(e);
}
}
}
1182

被折叠的 条评论
为什么被折叠?



