一.概述
和java.io.InputStream相反,java.io.OutStream是java标准库提供的最基本的输出流,它是一个抽象类,是所有输出流的超类。其中有一个write()方法,会写入输出流的下一个字节,写入int值(0~255)。
二.FileOutStream
与FileInputStream类似,这里只是简单说明一下区别。
package com.sdnu.project1;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author Beyong
* @Description FileOutStream
* @date 2021/05/24 20:46
*/
public class Demo3 {
public static void main(String[] args) {
FileOutputStream file = null;
try{
byte[] buffer = {97, 98, 99, 100, 101};
file = new FileOutputStream("myFile.txt");
file.write(buffer);
file.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- flush()用于刷新缓冲区数据,也就是将缓冲区的残留数据全部写如目的地,防止数据丢失。
- 我们上面的例子会覆盖原来文件的内容,如果我们想要追加,可以使用第二个构造函数,如下:
file = new FileOutputStream("myFile.txt",true);
三.实例
package com.sdnu.project1;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author Beyong
* @Description FileOutStream
* @date 2021/05/24 20:46
*/
public class Demo3 {
public static void main(String[] args) {
FileOutputStream file = null;
try{
String str = "I like China";
byte[] buffer = str.getBytes();
file = new FileOutputStream("myFile.txt",true);
file.write(buffer);
file.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我们通过getBytes()能将任意一个字符串变成字节数据,然后就可以写入了。
作者:Beyong
出处:Beyong博客
github地址:https://github.com/beyong2019
本博客中未标明转载的文章归作者Beyong有,欢迎转载,但未经作者同意必须保留此段声明,且在文章明显位置给出原文连接,否则保留追究法律责任的权利。