首页 > 代码库 > 将字节数组写出到文件的两种方式

将字节数组写出到文件的两种方式

方式1.ByteArrayInputStream

public static void writeBytesToFile() throws IOException{
        String s = "Some text";
        byte[] bs= s.getBytes();
        OutputStream out = new FileOutputStream("aaa.txt");
        InputStream is = new ByteArrayInputStream(bs);
        byte[] buff = new byte[1024];
        int len = 0;
        while((len=is.read(buff))!=-1){
            out.write(buff, 0, len);
        }
        is.close();
        out.close();
    }

 

方式2.FileChannel

public static void writeBytesToFile2() throws IOException{
        String s = "Some text2";
        byte[] bs= s.getBytes();
        
        ByteBuffer bb = ByteBuffer.wrap(bs);
        
        FileChannel fc = new FileOutputStream("aaaa.txt").getChannel();
        fc.write(bb);
        fc.close();
    }

 

将字节数组写出到文件的两种方式