package study;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
//在文件内容的尾部追加内容
public class Exercise2 {
public static void main(String[] args) {
//1.创建源
File f=new File("E:\\临时\\BBB.txt"); //没有此文件是会自动创建
//2.选择流
OutputStream o=null;
try {
o=new FileOutputStream(f,true);//加个true进入最加而不是覆盖了
//3.操作
String str="hello java";
byte[] b=str.getBytes(); //字符->字节==编码
o.write(b, 0, str.length());
o.flush(); //强制刷新,释放内存,最好习惯写这个
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
o.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
19.7 输出流OutputStream(追加写法)
最新推荐文章于 2025-10-14 12:07:22 发布
本文介绍了一个使用Java进行文件追加写入的示例代码,通过FileOutputStream流,将字符串“hellojava”追加到指定路径的文件末尾,而不会覆盖原有内容。代码展示了如何创建文件、选择流、进行写入操作并确保资源关闭。
1314

被折叠的 条评论
为什么被折叠?



