字节输出流FileOutputStream

本文介绍了Java中的FileOutputStream类如何使用write方法写入单个字节、字节数组以及字符串,包括换行符的处理,以及文件路径选项。初学者应注意可能存在的错误和细节。
摘要由CSDN通过智能技术生成

参数可输入字符串表示的路径或File对象

文件不存在会创建一个新文件,但要保证父级路径存在

若文件已存在,会清空文件

void write (int b) 写一个字节数据

public class aaa {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("a.txt");
        fos.write(97);
        fos.close();
    }
}

void write (byte[ ] b) 写一个字节数组数据

void write (byte[ ] b, int off, int len) 写一个字节数组的一段数据

off 是索引开始的下标, len 是写入的长度

public class aaa {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("a.txt");
        byte[] b={97,98,99,100,101};
        fos.write(b);//abcde
        fos.write(b,1,3);//bcd
        //最后结果为 abcdebcd, 因为没有输出换行
        fos.close();
    }
}

想输出长字串的话,可以把string 转byte[ ]

public class aaa {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("a.txt");
        String s="abcde";
        // 字符串转 byte数组
        byte[] b= s.getBytes();
        fos.write(b);
        fos.close();
    }
}

换行

Windows: \r\n    Linux: \n     Mac: \r

public class aaa {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("a.txt");
        fos.write(97);
        //换行
        String s="\r\n";
        byte[] b= s.getBytes();
        fos.write(b);

        fos.write(97);
        fos.close();
    }
}

续写

文件路径后输入 true ,默认为 false

FileOutputStream fos = new FileOutputStream("a.txt",true);

初学者,见解不足,如有错误请指出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值