java输入输出流:FileOutputStream

FileOutputStream常用方法:

public void write(int b)    //将指定字节写入此文件输出流
public void write(byte[] b)    //将b.length个字节从指定byte 数组写入此文件输出流中
public void write(byte[] b,int off,int len)    //将指定byte数组中从偏移量off开始的len个字节写入此文件输出流
public void close()     //关闭此文件输出流并释放与此流有关的所有系统资源

使用write(int b)方法向score.txt文件写入数据:

public static void main(String[] args) {
    try {
        FileOutputStream fos = new FileOutputStream("java_stream\\score.txt");
        fos.write(50);
        fos.write('a');
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e){
        e.printStackTrace();
    }
}

在这里插入图片描述
可以看到存入文件中的内容并不是我们输入的数据,这是因为编码的一些原因造成的,若将数据再输出,可以看到还是我们当时存入时的数据:

try {
    FileOutputStream fos = new FileOutputStream("java_stream\\score.txt");
    FileInputStream fis = new FileInputStream("java_stream\\score.txt");
    fos.write(50);
    fos.write('a');
    System.out.println(fis.read());
    System.out.println((char)fis.read());
    fis.close();
    fos.close();
    
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e){
    e.printStackTrace();
}
50
a

若写成FileOutputStream fos = new FileOutputStream("java_stream\\score.txt", true);
表示以追加的方式写入文件,而不是覆盖。
在这里插入图片描述
图片的读写和文件类似:
实现一个拷贝图片的过程。

public static void main(String[] args) {
    try {
        FileInputStream fis = new FileInputStream("java_stream\\animal.jpg");
        FileOutputStream fos = new FileOutputStream("java_stream\\animalcopy.jpg");
        byte[] b = new byte[1024];
        int n = 0;
        while((n = fis.read(b)) != -1){
            fos.write(b);
        }
        fis.close();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值