0

I am working on an Android app and trying to create a file of a certain size that won't be sparse. I literally want it to take up space on the Android device.

Here's what I have so far, I'm fairly new to Java and tried a couple different things to fill (takes waaay to long if the file is big like 5 GB) or append to the end (doesn't work? maybe I did it wrong).

        File file = new File(dir, "testFile.txt");

        try {
            RandomAccessFile f = new RandomAccessFile(file, "rw");
            f.setLength((long) userInputNum * 1048576 * 1024);
            f.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

Currently, what's happening is the file is created and say I want it to be 5 GB, in the file details it says it's 5 GB but it's not actually taking up space on the device (this is a sparse file as I have found out). How can I make it create the file not sparse or what's a quick way to fill the file? I can use a command on pc/mac to make the file and push it to the device but I want the app to do it.

4
  • What do you want the file to contain, if not sparse? Commented Mar 8, 2016 at 6:35
  • @DougStevenson anything but whatever is faster. I just want the storage to fill up quickly. It doesn't even have to be a text file if there's something else that will work better. I tried for example .mp4 or .zip but it was still sparse and I'm guessing that's expected. Commented Mar 8, 2016 at 6:45
  • Any reason why you can't just write empty arrays into a file until you've written the size you want? Commented Mar 8, 2016 at 6:46
  • @DougStevenson like I said, whatever fills the file, works. If you could show an example or hint me in the direction of how to do that, that would be great! (I'm not sure how to do what you're saying) Commented Mar 8, 2016 at 6:47

1 Answer 1

1

So this works:

            byte[] x = new byte[1048576];

            RandomAccessFile f = new RandomAccessFile(file, "rw");
            while(file.length() != (userInputNum * 1048576 * 1024))
            {
                f.write(x);
            }
            f.close();

Granted it is pretty slow, but I believe it's much faster creating a 10 GB file in app vs pushing a 10 GB file to the device. If someone has an idea of how to optimize this or change it completely, please do post!

How it works: It's writing to the file until the file has reached the size that the user wants. I believe I can do something different instead of byte[] but I'll leave that to whoever wants to figure that out. I'll do this on my own for myself, but hope this helps someone else!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.