FileOutputStream的使用
文章目录
一、FileOutputStream介绍
1.FileOutputStream——文件字节输出流,用于输出文件。
2.以字节的方式,完成输出(写)的操作(内存---->硬盘)
3.FileOutputStream的使用方法与FileInputStream相似,本文将简单介绍。
二、使用介绍
1.框架搭建
package IO;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamTest01 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("tempfile");
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2.write(int b) 与write(byte[] b, int off, int len) 的使用
与FileInputStream的read(byte[] b)和read(byte[] b, int off, int len)使用相似,详细可查看之前的文章:https://blog.csdn.net/m0_57497737/article/details/118659263.
package IO;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class FileOutputStreamTest01 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
//tempfile文件不存在时,会自动新建
fos = new FileOutputStream("tempfile");
//开始写
byte[] bytes = {97,98,99,100,101};
//将bytes数组全部写出
fos.write(bytes);
//将bytes数组的一部分写出
fos.write(bytes,4,1);
// String asl ="相信的心就是你的魔法!";
// byte[] ba = asl.getBytes();//将字符串转化为数组
// //将bs数组全部写出
// fos.write(ba);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
实现结果:
1.“tempfile”文件之前不存在,执行程序后已位于工程根目录新建。
2.文件内容
注意:
fos = new FileOutputStream(“tempfile”);这样使用会将原文件清空再写入,使用时要谨慎。
2.末尾处写入
想要不清空文件,只需要fos = new FileOutputStream(“tempfile”);写成fos = new FileOutputStream(“tempfile”,true);即可。
package IO;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class FileOutputStreamTest01 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
//tempfile文件不存在时,会自动新建
fos = new FileOutputStream("tempfile");
//开始写
byte[] bytes = {97,98,99,100,101};
//将bytes数组全部写出
fos.write(bytes);
//将bytes数组的一部分写出
fos.write(bytes,4,1);
String asl ="相信的心就是你的魔法!";
byte[] ba = asl.getBytes();//将字符串转化为数组
//将bs数组全部写出
fos.write(ba);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
执行结果: