Java中是否有原生类可存储文件的名称与字节数组内容?
Great question! Let's break this down clearly for you:
Java's core standard library does NOT have a native class specifically built to store both a filename and file content as a byte array. The JDK follows single-responsibility design principles here—classes that represent file system identifiers (like filenames or paths) don't hold in-memory content, and classes that handle byte data don't track file metadata like names.
Related JDK classes (but not a perfect match)
java.io.File/java.nio.file.Path: These only represent a file's location on the filesystem, not the actual content of the file. They're references to disk resources, not holders for in-memory byte arrays.byte[]: This is the raw storage for content, but it has no built-in way to associate a filename with the data.
Your current solution is actually ideal
The Document class you wrote with Lombok's @Value annotation is exactly what you need: it's immutable, concise, and perfectly encapsulates the two pieces of data you care about. If you ever need to drop Lombok, you can easily replicate it manually with a simple immutable class (including defensive copies to protect the byte array from external modifications):
import java.util.Objects; public final class Document { private final String fileName; private final byte[] content; public Document(String fileName, byte[] content) { this.fileName = Objects.requireNonNull(fileName, "fileName cannot be null"); this.content = Objects.requireNonNull(content, "content cannot be null").clone(); } public String getFileName() { return fileName; } public byte[] getContent() { return content.clone(); // Prevent external code from modifying the internal array } }
Alternatives (if you want to avoid custom classes)
Some third-party libraries have related types (like Apache Commons IO utilities or Spring's Resource), but these are far more heavyweight than your custom class and would add unnecessary dependencies. The core JDK has no native alternative that fits your exact requirements.
In short: stick with your custom Document class—it's the cleanest, most lightweight solution for your use case.
内容的提问来源于stack exchange,提问作者dermoritz

