IO流四个抽象及类
1.字节输出流,写入任意文件
OutputStream
write 字节数组 字节数组的一部分 单个字节
close 释放资源
flush 刷新资源,强制刷新资源
2.字节输入流,读取任意文件
InputStream
read 字节数组 字节数组的一部分 单个字节
close 关闭资源
3.字符输出流 读取文本文件
Write
write 字符输出 字节数组的一部分 单个字符 写字符串
flush 刷新内存,写完字符输出流必须强制刷新
close 关闭资源
4.字符输入流 读取文本文件
Reader
read 字符数组 字符数组的一部分 单个字符
close 关闭资源
package IODemo;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class FileOutputStreamDemo {
public static void main(String[] args) {
FileOutputStream fos = null;
FileOutputStream fos2 = null;
//开几个流对象就需要关闭多少流对象,在finally中添加try catch
try {
fos = new FileOutputStream("src/IODemo/test.txt",true);
fos2 = new FileOutputStream("src/IODemo/test.txt",true);
fos.write("我爱你".getBytes(StandardCharsets.UTF_8));
fos2.write("我爱你".getBytes(StandardCharsets.UTF_8));
}catch (IOException e ){
e.printStackTrace();
//此处如果发生异常,无法处理,则让程序停止运行
throw new RuntimeException("停止运行");
}finally {
try{
if(fos!=null){
fos.close();}
}catch (IOException e ) {
e.printStackTrace();
throw new RuntimeException("关闭异常");
}finally {
try {
if (fos2 != null) {
fos2.close();
}
} catch (IOException o) {
o.printStackTrace();
throw new RuntimeException("关闭异常");
}
}
}
}
public static void method_write() throws IOException {
FileOutputStream fos = new FileOutputStream("/Users/yuzhang/Desktop/test.txt");
//写入单个字节
fos.write("abc".getBytes(StandardCharsets.UTF_8));
//写入字节数组
byte[] bytes= {100,101,102,103};
fos.write(bytes);
fos.write("你好".getBytes(StandardCharsets.UTF_8));
fos.close();
}
public static void method_write1() throws IOException{
FileOutputStream fos = new FileOutputStream("src/IODemo/test.txt",true);
fos.write("中国".getBytes(StandardCharsets.UTF_8));
fos.close();
}
}