Common

Input/Output

Reflection

StreamHelper

The StreamHelper class provides static methods to perform common operations on Java streams. It focuses on simplifying the conversion of input streams to strings and efficiently copying data between streams.

Methods

1. copyToString(InputStream in)

Reads an input stream and converts it to a string using the default UTF-8 charset.

Example:

InputStream inputStream = new ByteArrayInputStream("Hello, World!".getBytes(StandardCharsets.UTF_8));
String content = StreamHelper.copyToString(inputStream);
System.out.println(content); // Output: Hello, World!\n

2. copyToString(InputStream in, Charset encode)

Reads an input stream and converts it to a string using the specified charset.

Example:

InputStream inputStream = new ByteArrayInputStream("你好,世界!".getBytes(StandardCharsets.UTF_8));
String content = StreamHelper.copyToString(inputStream, StandardCharsets.UTF_8);
System.out.println(content); // Output: 你好,世界!\n

3. read(InputStream in, Charset encode, Consumer<String> fn)

Reads the input stream line by line and applies the given consumer function to each line.

Example:

InputStream inputStream = new ByteArrayInputStream("Line 1\nLine 2\nLine 3".getBytes(StandardCharsets.UTF_8));
StreamHelper.read(inputStream, StandardCharsets.UTF_8, line -> {
    System.out.println("Line: " + line);
});
// Output:
// Line: Line 1
// Line: Line 2
// Line: Line 3

Unit Test Examples

package com.ajaxjs.util.io;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class TestStreamHelper {
    private InputStream inputStream;
    private String testString;

    @BeforeEach
    public void setUp() {
        testString = "测试字符串";
        inputStream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8));
    }

    @Test
    public void copyToString_WithDefaultCharset_ReturnsCorrectString() {
        String result = StreamHelper.copyToString(inputStream);
        assertEquals(testString + "\n", result);
    }

    @Test
    public void copyToString_WithSpecifiedCharset_ReturnsCorrectString() {
        String result = StreamHelper.copyToString(inputStream, StandardCharsets.UTF_8);
        assertEquals(testString + "\n", result);
    }
}

Note: The inputStream2Byte method is present in the test code but not in the provided StreamHelper class code.

Conclusion

The StreamHelper class provides a convenient way to perform common stream operations in Java. By using these methods, you can simplify your code and avoid writing repetitive stream I/O logic.