4.3.6 ByteArrayResource

原文应该有误(贴出如下): This is a Resource implementation for a given byte array. It creates a ByteArrayInputStream for the given byte array.

It’s useful for loading content from any given byte array, without having to resort to a single-use InputStreamResource. 然后附上ByteArrayResource源码,看个人注释

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.core.io;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import org.springframework.core.io.AbstractResource;

public class ByteArrayResource extends AbstractResource {
//通过一个字节数组来创建 `ByteArrayResource`。
    private final byte[] byteArray;
    private final String description;
//通过一个字节数组来创建 `ByteArrayResource`。
    public ByteArrayResource(byte[] byteArray) {
        this(byteArray, "resource loaded from byte array");
    }

    public ByteArrayResource(byte[] byteArray, String description) {
        if(byteArray == null) {
            throw new IllegalArgumentException("Byte array must not be null");
        } else {
            this.byteArray = byteArray;
            this.description = description != null?description:"";
        }
    }

    public final byte[] getByteArray() {
        return this.byteArray;
    }

    public boolean exists() {
        return true;
    }

    public long contentLength() {
        return (long)this.byteArray.length;
    }

    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(this.byteArray);
    }

    public String getDescription() {
        return "Byte array resource [" + this.description + "]";
    }

    public boolean equals(Object obj) {
        return obj == this || obj instanceof ByteArrayResource && Arrays.equals(((ByteArrayResource)obj).byteArray, this.byteArray);
    }

    public int hashCode() {
        return byte[].class.hashCode() * 29 * this.byteArray.length;
    }
}

这是针对字节数组提供的Resource实现。可以通过一个字节数组来创建 ByteArrayResource

当需要从字节数组加载内容时,ByteArrayResource 是一个不错的选择,使用 ByteArrayResource可以不用求助于 InputStreamResource

results matching ""

    No results matching ""