bestand naar byte [] in Java

Hoe converteer ik een java.io.Filenaar een byte[]?


1, Autoriteit 100%

Het hangt af van wat het beste voor u is. Productiviteit WISE, Herinner het wiel niet opnieuw en gebruik Apache Commons. Wat is hier FileUtils.readFileToByteArray(File input).


2, Autoriteit 254%

Van JDK 7 U kunt Files.readAllBytes(Path).

Voorbeeld:

import java.io.File;
import java.nio.file.Files;
File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());

3, Autoriteit 52%

Sinds JDK 7 Р̩̩n voering:

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

Geen externe afhankelijkheden nodig.


4, Autoriteit 31%

import java.io.RandomAccessFile;
RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);

Documentatie voor Java 8: http: // docs .oracle.com / javase / 8 / docs / api / java / io / randomaccessfile.html


5, Autoriteit 14%

Zoals iemand zei, Apache Commons Bestand Utils hebben mogelijk wat u zoekt

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

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

6, Autoriteit 5%

Als u Java 8 niet hebt en met mij eens bent dat inclusief een enorme bibliotheek om een ​​paar regels van de code te voorkomen een slecht idee is:

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

Beller is verantwoordelijk voor het sluiten van de stream.


Antwoord 7, autoriteit 4%

U kunt hiervoor ook de NIO-api gebruiken. Ik zou dit met deze code kunnen doen, zolang de totale bestandsgrootte (in bytes) maar in een int past.

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

Ik denk dat het erg snel is sinds het gebruik maakt van MappedByteBuffer.


Antwoord 8, autoriteit 4%

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

Antwoord 9, autoriteit 4%

Eenvoudige manier om het te doen:

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

Antwoord 10, autoriteit 4%

De eenvoudigste manier om bytes uit een bestand te lezen

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, Autoriteit 3%

Guava heeft bestanden.tobytearray () om u aan te bieden. Het heeft verschillende voordelen:

  1. Het heeft betrekking op het hoofdcase waarin bestanden een lengte van 0 melden, maar hebben nog steeds inhoud
  2. Het is zeer geoptimaliseerd, u krijgt een outofmemoryException als u probeert in een groot bestand te lezen voordat u het bestand zelfs probeert te laden. (Via slim gebruik van bestand.length ())
  3. U hoeft het wiel niet opnieuw uit te vinden.

12, Autoriteit 2%

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

13, Autoriteit 2%

Gebruik van dezelfde aanpak als het ANTWOORD van de Gemeenschap Wiki, maar schoner en compileer uit de doos (voorkeursbenadering Als u geen Apache Commons Libs wilt importeren, b.v. op Android):

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

Antwoord 14

Ik geloof dat dit de gemakkelijkste manier is:

org.apache.commons.io.FileUtils.readFileToByteArray(file);

Antwoord 15

ReadFullyLeest b.length bytes uit dit bestand in de byte-array, beginnend bij de huidige bestandsaanwijzer. Deze methode leest herhaaldelijk uit het bestand totdat het gevraagde aantal bytes is gelezen. Deze methode blokkeert totdat het gevraagde aantal bytes is gelezen, het einde van de stream wordt gedetecteerd of een uitzondering wordt gegenereerd.

RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);

Antwoord 16

Als je bytes in een vooraf toegewezen bytebuffer wilt lezen, kan dit antwoord helpen.

Uw eerste gok zou waarschijnlijk zijn om InputStream read(byte[]). Deze methode heeft echter een fout waardoor het onredelijk moeilijk te gebruiken is: er is geen garantie dat de array daadwerkelijk volledig gevuld zal zijn, zelfs als er geen EOF wordt aangetroffen.

Bekijk in plaats daarvan DataInputStream readFully(byte[]). Dit is een wrapper voor invoerstromen en heeft het bovengenoemde probleem niet. Bovendien gooit deze methode wanneer EOF wordt aangetroffen. Veel leuker.


Antwoord 17

Niet alleen converteert een java.io.File op de volgende manier naar een byte[], ik vond het ook de snelste manier om een bestand in te lezen bij het testen van veel verschillende Leesmethoden voor Java-bestandentegen elkaar:

java.nio.file.Files.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);
    }
  }
}

Antwoord 18

Laat me nog een oplossing toevoegen zonder bibliotheken van derden te gebruiken. Het hergebruikt een uitzonderingsverwerkingspatroon dat is voorgesteld door Scott(link). En ik heb het lelijke deel naar een apart bericht verplaatst (ik zou me verstoppen in een of andere FileUtils-klasse 😉 )

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

Antwoord 19

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

Antwoord 20

//The file that you wanna convert into byte[]
File file=new File("/storage/0CE2-EA3D/DCIM/Camera/VID_20190822_205931.mp4"); 
FileInputStream fileInputStream=new FileInputStream(file);
byte[] data=new byte[(int) file.length()];
BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
bufferedInputStream.read(data,0,data.length);
//Now the bytes of the file are contain in the "byte[] data"

21

Dit is een van de eenvoudigste manier

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

22

een andere manier voor het lezen van bytes uit bestand

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

23

Probeer dit:

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

24

kan zo eenvoudig worden gedaan als deze (KOTLIN-versie)

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

bewerken :

Ik heb documenten van readBytes-methode gelezen. Het zegt:

leest deze stroom volledig in een byte-array.
Opmerking : het is de verantwoordelijkheid van de beller om deze stroom te sluiten.

Dus om de stream te kunnen sluiten en alles schoon te houden, gebruik je de volgende code:

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

Met dank aan @user2768856 voor het wijzen hierop.


Antwoord 25

probeer dit als u een doelversie heeft van minder dan 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;
}

Antwoord 26

In JDK8

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

Other episodes