Alternative to java.nio.file.Files in Java 6

前端 未结 5 1760
北荒
北荒 2021-01-18 17:33

I have the following piece of code that uses the java 7 features like java.nio.file.Files and java.nio.file.Paths

import java.io.File;
impor         


        
5条回答
  •  旧巷少年郎
    2021-01-18 18:09

    You can read all bytes of a file into byte array even in Java 6 as described in an answer to a related question:

    import java.io.RandomAccessFile;
    import java.io.IOException;
    RandomAccessFile f = new RandomAccessFile(fileName, "r");
    if (f.length() > Integer.MAX_VALUE)
        throw new IOException("File is too large");
    byte[] b = new byte[(int)f.length()];
    f.readFully(b);
    if (f.getFilePointer() != f.length())
        throw new IOException("File length changed while reading");
    

    I added the checks leading to exceptions and the change from read to readFully, which was proposed in comments under the original answer.

提交回复
热议问题