Java--字节内存流--ByteArrayInputStream与ByteArrayOutputStream

原文网址:Java--字节内存流--ByteArrayInputStream与ByteArrayOutputStream_IT利刃出鞘的博客-CSDN博客

简介

说明

        本文介绍Java的字节内存流的用法。

概述

        如果要进行IO操作,但是不生成文件,就可以使用内存来实现输入与输出的操作。

对于内存流,java.io包里面提供了两组操作:

  • 字节内存流:ByteArrayInputStream、ByteArrayOutputStream
  • 字符内存流:CharArrayReader 、CharArrayWriter

        以下是以字节内存流操作为主;重点看一下ByteArrayInputStream、ByteArrayOutputStream的继承结构与构造方法:

示例:小写字母转换大写字母

需求

使用字节内存流,将“"Hello World ~ !"转为大写字母。

代码

package com.example.a;

import java.io.*;

public class Demo {
    public static void main(String[] args) throws IOException {
        String str = "Hello World ~ !";
        InputStream input = new ByteArrayInputStream(str.getBytes());
        OutputStream output = new ByteArrayOutputStream();

        int readResult = 0 ;
        while ((readResult = input.read()) != -1) {
            output.write(Character.toUpperCase(readResult));
        }
        System.out.println(output);
        input.close();
        output.close();
    }
}

结果

HELLO WORLD ~ !

示例:合并两个文件的内容

需求

使用内存字节流,将两个文件的内容读出来,然后合并到内存中。

代码

package com.example.a;

import java.io.*;

public class Demo {
    public static void main(String[] args) throws IOException {
        File file1 = new File("D:" + File.separator + "Document"
                + File.separator + "Document" + File.separator + "test1.txt");
        File file2 = new File("D:" + File.separator + "Document"
                + File.separator + "Document" + File.separator + "test2.txt");

        InputStream input1 = new FileInputStream(file1);
        InputStream input2 = new FileInputStream(file2);

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        int temp = 0;
        while ((temp = input1.read()) != -1) {
            output.write(temp);
        }
        while ((temp = input2.read()) != -1) {
            output.write(temp);
        }

        byte[] data = output.toByteArray();

        output.close();
        input1.close();
        input2.close();
        System.out.println(new String(data));
    }
}

猜你喜欢

转载自blog.csdn.net/feiying0canglang/article/details/126125854