Victor Oliveira
Victor Oliveira

Reputation: 3713

Limiting file size creation with java

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

           }

Upvotes: 0

Views: 3806

Answers (3)

Victor Oliveira
Victor Oliveira

Reputation: 3713

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..

Upvotes: 0

snrlx
snrlx

Reputation: 5107

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

Upvotes: 1

Kayaman
Kayaman

Reputation: 73558

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.

Upvotes: 0

Related Questions