如何将 java.io.File
转换为 byte[]
?
如何将 java.io.File
转换为 byte[]
?
从JDK 7开始,您可以使用Files.readAllBytes(Path)
方法。
示例:
import java.io.File;
import java.nio.file.Files;
File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());
File file = new File("/path");
Path path = Paths.get(file.getAbsolutePath());
byte[] data = Files.readAllBytes(path);
- gfelisberto这取决于你对“最好”一词的理解。就生产力而言,不要重复造轮子,使用Apache Commons库。它在这里:FileUtils.readFileToByteArray(File input)
。
File
读取成 byte[]
数组?由于使用的是 Java6,因此无法使用 NIO 方法 :( - P A S T R Y自 JDK 7 开始 - 一行代码:
byte[] array = Files.readAllBytes(Paths.get("/path/to/file"));
无需外部依赖。
import java.nio.file.Files;
和 import java.nio.file.Paths;
。 - Samimport java.io.RandomAccessFile;
RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);
Java 8的文档:http://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html
基本上你需要将它读入内存。打开文件,分配数组,并将文件内容读入数组。
最简单的方法类似于以下内容:
public byte[] read(File file) throws IOException, FileTooBigException {
if (file.length() > MAX_FILE_SIZE) {
throw new FileTooBigException(file);
}
ByteArrayOutputStream ous = null;
InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream(file);
int read = 0;
while ((read = ios.read(buffer)) != -1) {
ous.write(buffer, 0, read);
}
}finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
}
}
return ous.toByteArray();
}
这段代码存在一些不必要的文件内容复制(实际上数据被复制了三次:从文件到buffer
,从buffer
到ByteArrayOutputStream
,从ByteArrayOutputStream
到实际的结果数组)。
你还需要确保只在内存中读取特定大小的文件(通常这取决于应用程序):-)。
你还需要在函数外部处理IOException
异常。
另一种方法是:
public byte[] read(File file) throws IOException, FileTooBigException {
if (file.length() > MAX_FILE_SIZE) {
throw new FileTooBigException(file);
}
byte[] buffer = new byte[(int) file.length()];
InputStream ios = null;
try {
ios = new FileInputStream(file);
if (ios.read(buffer) == -1) {
throw new IOException(
"EOF reached while trying to read the whole file");
}
} finally {
try {
if (ios != null)
ios.close();
} catch (IOException e) {
}
}
return buffer;
}
这里没有不必要的复制。
FileTooBigException
是一个自定义的应用程序异常。 MAX_FILE_SIZE
常量是应用程序参数。
对于大文件,您可能应该考虑使用流处理算法或使用内存映射(请参见 java.nio
)。
正如有人所说,Apache Commons File Utils可能具有您正在寻找的功能
public static byte[] readFileToByteArray(File file) throws IOException
示例用法 (Program.java
):
import org.apache.commons.io.FileUtils;
public class Program {
public static void main(String[] args) throws IOException {
File file = new File(args[0]); // assume args[0] is the path to file
byte[] data = FileUtils.readFileToByteArray(file);
...
}
}
public static byte[] readBytes(InputStream inputStream) throws IOException {
byte[] b = new byte[1024];
ByteArrayOutputStream os = new ByteArrayOutputStream();
int c;
while ((c = inputStream.read(b)) != -1) {
os.write(b, 0, c);
}
return os.toByteArray();
}
调用方负责关闭流。
// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
throw new IOException("File is too large!");
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
InputStream is = new FileInputStream(file);
try {
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
} finally {
is.close();
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
return bytes;
}
您也可以使用NIO API来实现。只要文件总大小(以字节为单位)适合int,我就可以使用以下代码完成此操作。
File f = new File("c:\\wscp.script");
FileInputStream fin = null;
FileChannel ch = null;
try {
fin = new FileInputStream(f);
ch = fin.getChannel();
int size = (int) ch.size();
MappedByteBuffer buf = ch.map(MapMode.READ_ONLY, 0, size);
byte[] bytes = new byte[size];
buf.get(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fin != null) {
fin.close();
}
if (ch != null) {
ch.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
我认为它非常快,因为它使用了MappedByteBuffer。
简单的方法:
File fff = new File("/path/to/file");
FileInputStream fileInputStream = new FileInputStream(fff);
// int byteLength = fff.length();
// In android the result of file.length() is long
long byteLength = fff.length(); // byte count of the file-content
byte[] filecontent = new byte[(int) byteLength];
fileInputStream.read(filecontent, 0, (int) byteLength);