Java中将文件转换成byte[]

919

如何将 java.io.File 转换为 byte[]


我能想到的一个用途是从文件中读取序列化对象。 - Mahm00d
2
另一种方法是使用文件头查找文件类型。 - James P.
尝试以下代码:byte[] bytes = null; BufferedInputStream fileInputStream = null; try { File file = new File(filePath); fileInputStream = new BufferedInputStream(new FileInputStream(file)); //fileInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(this.filePath); bytes = new byte[(int) file.length()]; fileInputStream.read(bytes); } catch (FileNotFoundException ex) { throw ex; } - Rohit Chaurasiya
27个回答

4
public static byte[] readBytes(InputStream inputStream) throws IOException {
    byte[] buffer = new byte[32 * 1024];
    int bufferSize = 0;
    for (;;) {
        int read = inputStream.read(buffer, bufferSize, buffer.length - bufferSize);
        if (read == -1) {
            return Arrays.copyOf(buffer, bufferSize);
        }
        bufferSize += read;
        if (bufferSize == buffer.length) {
            buffer = Arrays.copyOf(buffer, bufferSize * 2);
        }
    }
}

4

让我再提供一种不使用第三方库的解决方案。它重用了一个异常处理模式,该模式是由Scott提出的(链接)。我将丑陋的部分移入了单独的消息中(我会隐藏在某个FileUtils类中 ;) )

public void someMethod() {
    final byte[] buffer = read(new File("test.txt"));
}

private byte[] read(final File file) {
    if (file.isDirectory())
        throw new RuntimeException("Unsupported operation, file "
                + file.getAbsolutePath() + " is a directory");
    if (file.length() > Integer.MAX_VALUE)
        throw new RuntimeException("Unsupported operation, file "
                + file.getAbsolutePath() + " is too big");

    Throwable pending = null;
    FileInputStream in = null;
    final byte buffer[] = new byte[(int) file.length()];
    try {
        in = new FileInputStream(file);
        in.read(buffer);
    } catch (Exception e) {
        pending = new RuntimeException("Exception occured on reading file "
                + file.getAbsolutePath(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                if (pending == null) {
                    pending = new RuntimeException(
                        "Exception occured on closing file" 
                             + file.getAbsolutePath(), e);
                }
            }
        }
        if (pending != null) {
            throw new RuntimeException(pending);
        }
    }
    return buffer;
}

2
另一种从文件中读取字节的方法。
Reader reader = null;
    try {
        reader = new FileReader(file);
        char buf[] = new char[8192];
        int len;
        StringBuilder s = new StringBuilder();
        while ((len = reader.read(buf)) >= 0) {
            s.append(buf, 0, len);
            byte[] byteArray = s.toString().getBytes();
        }
    } catch(FileNotFoundException ex) {
    } catch(IOException e) {
    }
    finally {
        if (reader != null) {
            reader.close();
        }
    }

不要使用空的 catch 块,这会使调试变得困难。 - Sapphire_Brick

2

Try this :

import sun.misc.IOUtils;
import java.io.IOException;

try {
    String path="";
    InputStream inputStream=new FileInputStream(path);
    byte[] data=IOUtils.readFully(inputStream,-1,false);
}
catch (IOException e) {
    System.out.println(e);
}

这需要特定的JRE实现,如果在另一个JRE上运行,将会破坏应用程序。 - rattaman
2
小错误:是IOException而不是IOexception,但谢谢:) - Matan Marciano
1
@MatanMarciano:我的错 - Sapphire_Brick

1

如果您的目标版本低于26 API,请尝试这个。

 private static byte[] readFileToBytes(String filePath) {

    File file = new File(filePath);
    byte[] bytes = new byte[(int) file.length()];

    // funny, if can use Java 7, please uses Files.readAllBytes(path)
    try(FileInputStream fis = new FileInputStream(file)){
        fis.read(bytes);
        return bytes;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;

}

1

可以这样简单地完成(Kotlin版本)

val byteArray = File(path).inputStream().readBytes()

编辑:

我已经阅读了readBytes方法的文档。它说:

将此流完全读入字节数组中。 注意: 关闭此流是调用者的责任。

因此,为了能够关闭流并保持一切清洁,请使用以下代码:

val byteArray = File(path).inputStream().use { it.readBytes() }

感谢 @user2768856 指出这一点。


1
使用 File(path).inputStream().use { it.readBytes() } 会自动关闭你的流。 - Vlad Sumtsov

-7

JDK8

Stream<String> lines = Files.lines(path);
String data = lines.collect(Collectors.joining("\n"));
lines.close();

2
读一下问题,我的讲法语的朋友,它要求将其转换为“byte []”,而你的答案没有提供这个。 - Kaiser Keister
2
这并没有提供任何远程选项来回答如何转换为byte[]! - Anddo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接