Файл в байт [] в Java - PullRequest
       86

Файл в байт [] в Java

667 голосов
/ 13 мая 2009

Как конвертировать java.io.File в byte[]?

Ответы [ 23 ]

1171 голосов
/ 22 февраля 2011

С 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());
439 голосов
/ 13 мая 2009

Зависит от того, что лучше для вас значит. Производительность мудрая, не изобретайте велосипед и используйте Apache Commons. Который здесь IOUtils.toByteArray(InputStream input).

159 голосов
/ 08 декабря 2011
import 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

150 голосов
/ 02 июля 2015

С JDK 7 - один вкладыш:

byte[] array = Files.readAllBytes(Paths.get("/path/to/file"));

Внешние зависимости не нужны.

76 голосов
/ 13 мая 2009

В основном вы должны прочитать это в памяти. Откройте файл, выделите массив и прочитайте содержимое файла в массив.

Самый простой способ примерно такой:

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).

68 голосов
/ 13 мая 2009

Как кто-то сказал, 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);
        ...
    }
}
22 голосов
/ 13 мая 2009

Вы можете использовать API-интерфейс NIO, чтобы сделать это. Я мог бы сделать это с этим кодом до тех пор, пока общий размер файла (в байтах) поместится в 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.

19 голосов
/ 07 июля 2016

Если у вас нет Java 8, и вы согласны со мной, что включение массивной библиотеки во избежание написания нескольких строк кода - плохая идея:

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();
}

Вызывающий абонент отвечает за закрытие потока.

19 голосов
/ 13 мая 2009
// 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;
    }
16 голосов
/ 23 февраля 2017

Простой способ сделать это:

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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...