JAVA文件输出流FileOutputStream

JAVA文件输出流FileOutputStream

父类

输入流输出流
字节流字节输入流
InputStream
字节输出流
OutputStream
字符流字符输入流
Reader
字符输出流
Writer
package JAVA_Test7;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * * `public FileOutputStream(File file)`:创建文件输出流以写入由指定的 File对象表示的文件。
 * * `public FileOutputStream(String name)`: 创建文件输出流以指定的名称写入文件。
 * FileOutputStream构造函数会自动创建一个新文件a.text并写入字节数据
 *
 */
public class OutPutStream {
    public static void main(String[] args) throws IOException {
        FileOutputStream fo = new FileOutputStream("F:\\Users\\xm\\下载\\文件\\day09_字节流、字符流\\a.text");
        fo.write(97);
        fo.write(98);
        fo.write(99);
        byte [] bytes = "你好".getBytes();
        fo.write(bytes);
    }
}

在这里插入图片描述

FileOutputStream默认创建一个新文件覆盖可能存在的同名文件,那么如何不覆盖追加写入数据?
构造方法FileOutputStream(File file, boolean append)
FileOutputStream(String name, boolean append)

第二个参数改为true即可

 FileOutputStream fo = new FileOutputStream("F:\\Users\\xm\\下载\\文件\\day09_字节流、字符流\\a.text",true);

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以按照以下步骤实现: 1. 创建一个Map对象,将需要存储的对象放入其中。 例如,假设需要存储一个名为person的对象,可以这样创建Map对象: ``` Map<String, Object> map = new HashMap<>(); map.put("person", person); ``` 2. 创建一个文件输出对象和一个对象输出对象。 ``` FileOutputStream fileOutputStream = new FileOutputStream("map.txt"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); ``` 3. 使用对象输出对象将Map对象写入到文件中。 ``` objectOutputStream.writeObject(map); ``` 4. 关闭对象输出文件输出。 ``` objectOutputStream.close(); fileOutputStream.close(); ``` 完整的代码示例如下: ``` import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { // 创建一个Person对象 Person person = new Person("Tom", 20); // 创建一个Map对象,将Person对象放入其中 Map<String, Object> map = new HashMap<>(); map.put("person", person); try { // 创建文件输出和对象输出 FileOutputStream fileOutputStream = new FileOutputStream("map.txt"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); // 将Map对象写入文件中 objectOutputStream.writeObject(map); // 关闭输出 objectOutputStream.close(); fileOutputStream.close(); } catch(IOException e) { e.printStackTrace(); } } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } ``` 执行完上述代码后,文件"map.txt"中将会存储一个包含了Person对象的Map对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

葛济维的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值