OutputStream类讲解FileOutputStream类、BufferedOutputStream类
OutputStream类 之 FileOutputStream类:文件字节输出流
try {
OutputStream fos = new FileOutputStream("F:\\OutputStreamDemo.txt");
// FileOutputStream fos = new FileOutputStream("F:\\OutputStreamDemo.txt", true);
fos.write("yeah".getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/*
解释:
1、FileOutputStream的参数问题:
- FileOutputStream中的第一个参数可以传入文件对象,也可以传入文件路径
- 第二个参数可以是false也可以是true,其代表的意思是是否在原有基础上追加内容,如果第二个参数不写,默认为false
- 如果参数为false,即重新写入,那么文件原有内容会删除
2、write(byte b[])方法:
- 该方法的参数是一个字节数组,如果你想写入字符串,那么需要用到String类的getBytes方法将字符串转为字节数组
- fos.write("yeah".getBytes());等同于
- byte[] buffer = new byte[10];
buffer = "hi".getBytes();
fos.write(buffer);
*/
OutputStream类 之 BufferedOutputStream类:带缓冲的字节输出流
try {
OutputStream fos = new FileOutputStream("F:\\OutputStreamDemo.txt");
//FileOutputStream fos = new FileOutputStream("F:\\OutputStreamDemo.txt", true);
BufferedOutputStream bos = new BufferedOutputStream(fos); // Buffere包装其他类,注意参数
bos.write("hello".getBytes());
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}