Reading a binary input stream into a single byte array in Java

前端 未结 6 1924
陌清茗
陌清茗 2020-11-27 18:10

The documentation says that one should not use available() method to determine the size of an InputStream. How can I read the whole content of an <

6条回答
  •  星月不相逢
    2020-11-27 18:47

    Please keep in mind that the answers here assume that the length of the file is less than or equal to Integer.MAX_VALUE(2147483647).

    If you are reading in from a file, you can do something like this:

        File file = new File("myFile");
        byte[] fileData = new byte[(int) file.length()];
        DataInputStream dis = new DataInputStream(new FileInputStream(file));
        dis.readFully(fileData);
        dis.close();
    

    UPDATE (May 31, 2014):

    Java 7 adds some new features in the java.nio.file package that can be used to make this example a few lines shorter. See the readAllBytes() method in the java.nio.file.Files class. Here is a short example:

    import java.nio.file.FileSystems;
    import java.nio.file.Files;
    import java.nio.file.Path;
    
    // ...
            Path p = FileSystems.getDefault().getPath("", "myFile");
            byte [] fileData = Files.readAllBytes(p);
    

    Android has support for this starting in Api level 26 (8.0.0, Oreo).

提交回复
热议问题