Limiting file size creation with java

醉酒当歌 提交于 2019-12-13 04:30:34

问题


Im trying to limit the size creation of one file in my java app. For that I made this sample code which I declare one variable lenght of 32 bytes, start WriteOnFile method looping it until 32 bytes. The problem is, it doesnt matter the value I set set on FILE_SIZE (Higher or lower) the download file is always coming with 400kb - that means my code is working since the original file is 200Mb but has some logic mistake. is there another way to do this? cos I based myself on this post How to limit the file size in Java and until now found nothing better

I was wondering if this has something with the bufferedwriter...

Thanks in advance for the help

public static final byte FILE_SIZE = 32;   

 private static void WriteOnFile(BufferedWriter writer, String crawlingNode){

               try {
                   while(file.length()<FILE_SIZE){

                    writer.write(crawlingNode);
                    System.out.println(file.length());
                   }
            } catch (IOException e) {

                JOptionPane.showMessageDialog(null, "Failed to write URL Node");
                    e.printStackTrace();            
            }

           }

回答1:


I just tried around a little bit and I could write files that are 32 bytes large by limiting the BufferedWriter's write-method directly:

        writer.write(crawlingNode, 0, 32);

With that call, only the first 32 chars are written to the file. As my encoding was UTF-8, which means that every char occupies one byte, the size of my output file was only 32 bytes. Writing only 16 chars resulted in a file of 16 bytes and so forth.

So maybe you could use that without implementing some other big stuff.

EDIT:

If your String has less characters than 32, then use the following call:

writer.write(crawlingNode, 0, crawlingNode.length);



回答2:


Use the stream to limit the file size, don't rely on file.length().

Apache Commons has this http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/output/CountingOutputStream.html

But you can easily write your own as well.




回答3:


I found my own answer. Yes, this has to be with Buffered writer. The Buffered writer has a default buffer of 8kb to READ. To write this buffer is dumped every 400kb in my app case. To write the file with one lower size we need to use another way to write like OutputSteam..



来源:https://stackoverflow.com/questions/17746114/limiting-file-size-creation-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!