Plik do bajtu [] w Javie

Jak przekonwertować java.io.File na byte[]?

 571
Author: Duncan Jones, 2009-05-13

21 answers

To zależy od tego, co dla ciebie znaczy najlepiej. Jeśli chodzi o produktywność, nie wymyślaj koła na nowo i nie używaj Apache Commons. Który jest tutaj IOUtils.toByteArray(InputStream input).

 391
Author: svachon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-01 12:26:45

Z JDK 7 możesz użyć Files.readAllBytes(Path).

Przykład:

import java.io.File;
import java.nio.file.Files;

File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());
 1052
Author: Michael Pollmeier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-03 07:42:00
import java.io.RandomAccessFile;
RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);

Dokumentacja dla Java 8: http://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html

 154
Author: Dmitry Mitskevich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-19 12:20:31

Od JDK 7-One liner:

byte[] array = Files.readAllBytes(new File("/path/to/file").toPath());

Nie są potrzebne zewnętrzne zależności.

 128
Author: Paulius Matulionis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-15 12:57:50

W zasadzie trzeba to przeczytać w pamięci. Otwórz plik, przydziel tablicę i wczytaj zawartość z pliku do tablicy.

Najprostszy sposób jest podobny do tego:

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

Powoduje niepotrzebne kopiowanie zawartości pliku (w rzeczywistości dane są kopiowane trzy razy: z pliku do buffer, z buffer do ByteArrayOutputStream, z ByteArrayOutputStream do rzeczywistej tablicy wynikowej).

Musisz również upewnić się, że czytasz w pamięci tylko pliki o określonym rozmiarze (jest to zazwyczaj zależne od aplikacji): -).

Musisz również traktować IOException poza funkcją.

Inny sposób jest taki:

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

To nie ma zbędnego kopiowania.

FileTooBigException jest wyjątkiem aplikacji niestandardowej. Stała MAX_FILE_SIZE jest parametrem aplikacji.

W przypadku dużych plików powinieneś pomyśleć o algorytmie przetwarzania strumienia lub użyć mapowania pamięci(zobacz java.nio).

 72
Author: Mihai Toader,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-19 13:52:56

Jak ktoś powiedział, Plik Apache Commons Utils może mieć to, czego szukasz

public static byte[] readFileToByteArray(File file) throws IOException

Przykładowe użycie (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);
        ...
    }
}
 64
Author: Tom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-03 21:05:57

Możesz również użyć API NIO. Mógłbym to zrobić z tym kodem, o ile całkowity Rozmiar pliku (w bajtach) zmieściłby się w 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();
    }
}

Myślę, że jest bardzo szybki, ponieważ używa MappedByteBuffer.

 19
Author: Amit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-12 19:39:31
// 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;
    }
 17
Author: Cuga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-15 16:23:13

Jeśli nie masz Javy 8 i zgadzasz się ze mną, że dołączenie ogromnej biblioteki, aby uniknąć pisania kilku linijek kodu, jest złym pomysłem:

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

Rozmówca jest odpowiedzialny za zamknięcie strumienia.

 16
Author: Jeffrey Blattman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-12 19:37:36

Prosty sposób na to:

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);
 13
Author: Sudip Bhandari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-12 19:33:49

Najprostszy sposób odczytu bajtów z pliku

import java.io.*;

class ReadBytesFromFile {
    public static void main(String args[]) throws Exception {
        // getBytes from anyWhere
        // I'm getting byte array from File
        File file = null;
        FileInputStream fileStream = new FileInputStream(file = new File("ByteArrayInputStreamClass.java"));

        // Instantiate array
        byte[] arr = new byte[(int) file.length()];

        // read All bytes of File stream
        fileStream.read(arr, 0, arr.length);

        for (int X : arr) {
            System.out.print((char) X);
        }
    }
}
 11
Author: Muhammad Sadiq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-12 19:36:02

Guawa ma Pliki.toByteArray () do zaoferowania. Ma kilka zalet:

  1. obejmuje przypadek narożny, w którym pliki zgłaszają Długość 0, ale nadal mają zawartość
  2. jest wysoce zoptymalizowany, dostajesz OutOfMemoryException, jeśli próbujesz przeczytać w dużym pliku, zanim nawet spróbujesz załadować plik. (Dzięki sprytnemu wykorzystaniu plików.length ())
  3. Nie musisz odkrywać koła na nowo.
 10
Author: jontejj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-17 15:12:02

Korzystanie z tego samego podejścia co community wiki answer, ale czystsze i kompilowanie po wyjęciu z pudełka (preferowane podejście, jeśli nie chcesz importować bibliotek Apache Commons, np. na Androida):

public static byte[] getFileBytes(File file) throws IOException {
    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) {
            // swallow, since not that important
        }
        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
            // swallow, since not that important
        }
    }
    return ous.toByteArray();
}
 8
Author: manmal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-24 13:00:22
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

File file = getYourFile();
Path path = file.toPath();
byte[] data = Files.readAllBytes(path);
 8
Author: BlondCode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-02 15:55:06

Wierzę, że jest to najprostszy sposób:

org.apache.commons.io.FileUtils.readFileToByteArray(file);
 5
Author: Cristian Tetic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-03 12:44:25

Odczyt odczytuje bajty B. długości z tego pliku do tablicy bajtów, zaczynając od bieżącego wskaźnika pliku. Metoda ta odczytuje z pliku wiele razy, aż do odczytania wymaganej liczby bajtów. Metoda ta blokuje do momentu odczytania żądanej liczby bajtów, wykrycia końca strumienia lub wyrzucenia wyjątku.

RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);
 4
Author: Tarun M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-16 08:13:32

Pozwól mi dodać inne rozwiązanie bez korzystania z bibliotek innych firm. Ponownie używa wzorca obsługi wyjątków zaproponowanego przez Scotta (link). I przeniosłem brzydką część do osobnej wiadomości (schowałem się w jakiejś klasie 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;
}
 3
Author: Andreas_D,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:29

Jeśli chcesz odczytać bajty do wstępnie przydzielonego bufora bajtów, ta odpowiedź może pomóc.

Twoim pierwszym podejściem prawdopodobnie byłoby użycie InputStream read(byte[]). Metoda ta ma jednak wadę, która sprawia, że jest ona nieracjonalnie trudna w użyciu: nie ma gwarancji, że tablica zostanie rzeczywiście całkowicie wypełniona, nawet jeśli nie napotkamy EOF.

Zamiast tego spójrz na DataInputStream readFully(byte[]). Jest to opakowanie dla strumieni wejściowych i nie ma wyżej wymienionego problemu. Dodatkowo metoda ta rzuca po napotkaniu EOF. O wiele milszy.

 3
Author: Laurens Holst,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-12 21:03:10
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);
        }
    }
}
 2
Author: mazatwork,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-12 11:33:27

Inny sposób odczytu bajtów z pliku

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();
        }
    }
 1
Author: Muhammad Aamir Ali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-25 10:24:34

Poniższy sposób nie tylko konwertuje plik java.io.na bajt[], ale również okazało się, że jest to najszybszy sposób odczytu w pliku, podczas testowania wielu różnych metod odczytu plików Java przeciwko sobie:

Java.nio.plik.Pliki.readAllBytes ()

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class ReadFile_Files_ReadAllBytes {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    byte [] fileBytes = Files.readAllBytes(file.toPath());
    char singleChar;
    for(byte b : fileBytes) {
      singleChar = (char) b;
      System.out.print(singleChar);
    }
  }
}
 0
Author: gomisha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-09 13:38:22