首页 > 其他分享 >io流-字节输出流写多个字节的方法

io流-字节输出流写多个字节的方法

时间:2022-10-17 10:58:38浏览次数:56  
标签:字节 fos bytes FileOutputStream io 流写 byte txt

字节输出流写多个字节的方法

public void write(byte[] b):将b.length字节从指定的字节数组写入此输出流

一次写入多个字节:

如果写的第一个字节是正数(0-127)那么显示的时候回查询ASCII表

如果写的第一个字节是负数,那第一个字节会和第二个字节 两个字节组成一个中午显示 查询系统默认码表(GBK)

代码:

复制代码
public static void main(String[] args) throws Exception {
        //创建FileOutputStream对象
        FileOutputStream fos = new FileOutputStream("E:\\file\\b.txt");
        //写入数据
        //创建byte[]数组
        byte[] bytes={97,98,99,100};
        fos.write(bytes);

        fos.close();
    }
复制代码

执行前:

 

 运行结果:

 

 执行后

b.txt

 

 public void write(byte[] b,int off,int len):把字节数组的一部分写入到文件中

int off:数组的开始索引

int len:写几个字节

代码:

复制代码
 public static void main(String[] args) throws Exception {
        //创建FileOutputStream对象
        FileOutputStream fos = new FileOutputStream("E:\\file\\b.txt");
        //写入数据
        //创建byte[]数组
        //需求值要bc其它的不要
        byte[] bytes={97,98,99,100};
        fos.write(bytes,1,2);

        fos.close();
    }
复制代码

b.txt

 

 运行结果:

 

 执行后:

 

 写入字符串的方法:可以使用String类中的方法把字符串 转换为字节数组

byte[] getBytes() 把字符串转为字节数组】

代码:

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

        fos.close();
    }
复制代码

执行前:

 

 运行结果:

 

 执行后:

标签:字节,fos,bytes,FileOutputStream,io,流写,byte,txt
From: https://www.cnblogs.com/shenziyi/p/16798398.html

相关文章