Java官方操縱byte數組的方式


java官方提供了一種操作字節數組的方法——內存流(字節數組流)ByteArrayInputStream、ByteArrayOutputStream

ByteArrayOutputStream——byte數組合並

/**
    * 將所有的字節數組全部寫入內存中,之后將其轉化為字節數組
    */
    public static void main(String[] args) throws IOException {
        String str1 = "132";
        String str2 = "asd";
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        os.write(str1.getBytes());
        os.write(str2.getBytes());
        byte[] byteArray = os.toByteArray();
        System.out.println(new String(byteArray));
    }

 

ByteArrayInputStream——byte數組截取

/**
    *   從內存中讀取字節數組
    */
    public static void main(String[] args) throws IOException {
        String str1 = "132asd";
        byte[] b = new byte[3];
        ByteArrayInputStream in = new ByteArrayInputStream(str1.getBytes());
        in.read(b);
        System.out.println(new String(b));
        in.read(b);
        System.out.println(new String(b));
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM