OutputStream是输出字节流的父类,它是一个抽象类
FileOutputStream
把内存中的数据以字节的形式写出到磁盘文件中的输出流,用于将数据写出到文件。
它继承自 OutputStream 类。通过创建 FileOutputStream 对象,可以打开一个文件,并向该文件中写入数据。可以使用 write(int) 方法逐个字节地写入数据,也可以使用 write(byte[]) 方法一次写入多个字节。写入完成后,应该调用 close() 方法关闭流。
应用实例:请使用FileOutputStream 在a.txt 文件中写入”hello,world“,如果文件不存在,会自动创建文件
第一种方法:使用 write(int b) 注意关闭文件流,或刷新文件流
OutputStream os = new FileOutputStream("src/a.txt");
os.write('a');
os.write('b');
os.flush();
os.close();
第二种方法:使用 write(byte[] b)
OutputStream os = new FileOutputStream("src/a.txt");
byte[] b = {'c','b','c'};
os.write(b);
os.close();
os.write("我是中国人".getBytes());
不要把之前数据清空,追加
FileOutputStream,append true
写前几个
byte[] b = {'c','b','d'};
os.write(b,0,2);
换行
os.write('a');
os.write("\r\n".getBytes());
os.write('b');
第三种方法:使用 write(byte[] b,int off,int len)
public class FileOutputStream01 {
public static void main(String[] args) {
}
@Test
public void writeFile(){
String filePath = "D:\\a.txt";
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath);
//写入一个字符串
String str = "hello,Jay!";
fileOutputStream.write(str.getBytes(),0,str.length());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
练习:将枯藤老树昏鸦,小桥流水人家,古道西风瘦马,夕阳西下,断肠人在天涯 出入到文件里
OutputStream out = new FileOutputStream("d:\\2.txt", true);
try {
String ss = "枯藤老树昏鸦,小桥流水人家,古道西风瘦马,夕阳西下,断肠人在天涯";
byte[] bytes = ss.getBytes();//getBytes()方法把字符串转为字节数组
out.write(bytes);
}catch (Exception ex){
ex.printStackTrace();
}finally {
out.flush();
out.close();
}