Java中的IO流(FileOutputStream)

FileOutputStream:

  • (文件字节输出流)

    • 此抽象类是表示输出字节流的所有类的超类。输出流接受输出字节并将这些字节发送到某个接收器 (文件)。
    • 需要定义 OutputStream 子类的应用程序必须始终提供至少一种可写入一个输出字节的方法。
    • FileOutputStream:文件字节输出流
    • 注意:OutputStream os = new FileOutputStream(“a.txt”, false); 覆盖文件之前的内容
    • OutputStream os = new FileOutputStream(“a.txt”, true); 追加文件的内容
    • 注意:流关闭之后就不能写入数据了
    • 面试题:flush和close的区别
  • flush:刷空流,不关闭流

  • close:既有刷空流的作用,还有关闭流的作用

  • close其实只是一个通知的作用,告诉虚拟机,文件传输完毕你来关闭流

public static void main(String[] args) throws IOException {
	//1:创建一个输出流 (创建管道)  既能创建流管道,还能创建文件
	FileOutputStream os = new FileOutputStream("a.txt", false);
	//2:往文件写数据
	  //2.1 一次写入一个字节
	  os.write(97);
	  os.write(98);
	  os.write(99);
	  os.write(100);
	  os.write(101);
	
	  //2.2 一次写入一个字节数组
	  byte[] by = {97,98,99,100,101};
	  os.write(by);
	  //2.3 一次写入一个字节数组的一部分
	  os.write(by, 1, 3);

	  //刷空流
	   os.flush();
	  //3:关闭流
	   os.close();
	   os.write(120);
	
	
}

猜你喜欢

转载自blog.csdn.net/qq_44013790/article/details/85267419