首页 > 其他分享 >io流-数据追加续写

io流-数据追加续写

时间:2022-10-17 10:57:10浏览次数:45  
标签:文件 fos getBytes FileOutputStream io txt 续写 public 追加

数据追加续写

经过以上的演示 每次程序运行 创建输出流对象 都会清空目标文件中的数据 如果保留目标文件中数据 还能继续添加新的数据

构造方法

public FileOutputStream(File file,boolean append):创建文件输出流以写入由指定的File对象表示文件
public FileOutputStream(String name,boolean append):创建文件输出流以指定的名称写入文件

这两个构造方法 参数中都需要传入一个boolean类型的值 true表示追加数据 false表示清空原有数据 这样创建的输出流对象 就可以指定是否追加续写

b.txt:

 b.txt里已经有字节 你好 接下来写字符串“世界”

代码:

复制代码
public static void main(String[] args) throws Exception {
        //创建FileOutputStream对象
        FileOutputStream fos = new FileOutputStream("E:\\file\\b.txt",true);
        //将你好写入到b.txt的文件
        byte[] bytes = "世界".getBytes();
        fos.write(bytes);

        fos.close();
    }
复制代码

运行结果:

 b.txt:

 已经成功追加 但是这样写会出现另一个文件 就是两个字符串挤在一起看的比较别扭 不舒服

我们可以使用系统自带的换行符号

\r\n相当于我们的回车

/n相当于我们的回车

/t相当于我们的tab键

这里我们可以使用/t

代码:

复制代码
public static void main(String[] args) throws Exception {
        //创建FileOutputStream对象
        FileOutputStream fos = new FileOutputStream("E:\\file\\b.txt",false);
        //将你好写入到b.txt的文件
        fos.write("你好".getBytes());
        fos.write("\t".getBytes());
        fos.write( "世界".getBytes());


        fos.close();
    }
复制代码

运行结果:

 b.txt:

标签:文件,fos,getBytes,FileOutputStream,io,txt,续写,public,追加
From: https://www.cnblogs.com/shenziyi/p/16798405.html

相关文章