zoukankan      html  css  js  c++  java
  • 字节数组输入流写出操作

    和文件的写出类似,稍有不同

    不同之处为在文件写出中需要关联文件

    OutputStream os = new BufferedOutputStream(new FileOutputStream("F:/win10/test/aCopy.txt"));
            // 或者
            os = new BufferedOutputStream(new FileOutputStream(new File("F:/win10/test/aCopy.txt")));

    而在ByteArrayOutputStream中不关联文件,且不能使用多态

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    完整代码如下

    package com.machuang.io.others;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    public class ByteArray {
    
        public static void main(String[] args) throws IOException {
    //        byteArrayRead();
            byte[] recBytes = byteArrayWrite();
            System.out.println(new String(recBytes, 0, recBytes.length));
    
        }
    
        public static byte[] byteArrayWrite() throws IOException {
            // 创建需要写出的字节数组
            String msg = "和文件写出类似,稍有不同";
            byte[] sentData = msg.getBytes();
            
            // 创建 ByteArrayOutputStream对象
            // 注意:此处需要使用 ByteArrayOutputStream对象的新方法,不能使用多态
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            
            // 写出
            bos.write(sentData, 0, sentData.length);
            
            byte[] receiveBuf = bos.toByteArray(); // new function
            
            bos.close();
    
            return receiveBuf;
        }
        
        
        
    }
    
        
  • 相关阅读:
    常见算法:C语言求最小公倍数和最大公约数三种算法
    java数据结构
    创建与删除索引
    Delphi 2007体验!
    wxWindows
    Android中WebView的相关使用
    IAR FOR ARM 各版本号,须要的大家能够收藏了
    [AngularJS] $interval
    [ES6] 10. Array Comprehensions
    [ES6] 09. Destructuring Assignment -- 2
  • 原文地址:https://www.cnblogs.com/cappuccinom/p/8822078.html
Copyright © 2011-2022 走看看