Most Robust way of reading a file or stream using Java (to prevent DoS attacks)

后端 未结 7 453
长情又很酷
长情又很酷 2020-12-04 13:51

Currently I have the below code for reading an InputStream. I am storing the whole file into a StringBuilder variable and processing this string af

7条回答
  •  庸人自扰
    2020-12-04 13:58

    I faced a similar issue when copying a huge binary file (which generally does not contain newline character). doing a readline() leads to reading the entire binary file into one single string causing OutOfMemory on Heap space.

    Here is a simple JDK alternative:

    public static void main(String[] args) throws Exception
    {
        byte[] array = new byte[1024];
        FileInputStream fis = new FileInputStream(new File(""));
        FileOutputStream fos = new FileOutputStream(new File(""));
        int length = 0;
        while((length = fis.read(array)) != -1)
        {
            fos.write(array, 0, length);
        }
        fis.close();
        fos.close();
    }
    

    Things to note:

    • The above example copies the file using a buffer of 1K bytes. However, if you are doing this copy over network, you may want to tweak the buffer size.

    • If you would like to use FileChannel or libraries like Commons IO, just make sure that the implementation boils down to something like above

提交回复
热议问题