java–io流之字节流写入与读取数据
一、字节流输出数据(FileOutputStream)
第一部分
FileOutputSteam的构造器因为我传了个true,这个true是用来实现追加效果的,也就是你再次运行这段代码的时候它会在原本这个文件内容的基础上追加代码中新写入的内容,不会因为每次运行而刷新掉之前的内容
初始示例(未处理异常版本)
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class test {
public static void main(String[] args) throws IOException {
FileOutputStream fo = new FileOutputStream("haha.txt", true);
String string = "abcd";
/*
字节流实现换行:
win: \r\n
linux \n
mac \r
*/
String string2 = "\r\n";
for (int i = 0; i < 2; i++) {
//传入的是一个字节数组
fo.write(string.getBytes(StandardCharsets.UTF_8),1,3);
//因为是静态方法所以可以不需要创建对象直接使用
fo.write("\r\n".getBytes(StandardCharsets.UTF_8));
fo.write("ABCD".getBytes(StandardCharsets.UTF_8),1,3);
//两次换行效果,用来区分下次追加的内容
fo.write(string2.getBytes(StandardCharsets.UTF_8));
fo.write(string2.getBytes(StandardCharsets.UTF_8));
}
fo.close();//关闭io流对象,释放系统资源
}
}
第二部分
我们要处理异常的原因
这一部分非常重要
io流中有很多的风险,因为是编译型异常,不处理异常的话无法正常编译
我们在上面例子中只是用了throws处理了
我们下面用trycatchfinally来正式处理
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets