tonyloban
tonyloban

Reputation: 49

How to create a file in Java of certain size (not sparse)

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.

Upvotes: 0

Views: 868

Answers (1)

tonyloban
tonyloban

Reputation: 49

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!

Upvotes: 1

Related Questions