Java create file with size

Create file with given size in Java

Create a new RandomAccessFile and call the setLength method, specifying the desired file length. The underlying JRE implementation should use the most efficient method available in your environment.

on a Linux machine will allocate the space using the ftruncate(2)

6070 open("t", O_RDWR|O_CREAT, 0666) = 4 6070 fstat(4, ) = 0 6070 lseek(4, 0, SEEK_CUR) = 0 6070 ftruncate(4, 1073741824) = 0 

while on a Solaris machine it will use the the F_FREESP64 function of the fcntl(2) system call.

/2: open64("t", O_RDWR|O_CREAT, 0666) = 14 /2: fstat64(14, 0xFE4FF810) = 0 /2: llseek(14, 0, SEEK_CUR) = 0 /2: fcntl(14, F_FREESP64, 0xFE4FF998) = 0 

In both cases this will result in the creation of a sparse file.

Solution 2

Since Java 8, this method works on Linux and Windows :

final ByteBuffer buf = ByteBuffer.allocate(4).putInt(2); buf.rewind(); final OpenOption[] options = < StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW , StandardOpenOption.SPARSE >; final Path hugeFile = Paths.get("hugefile.txt"); try (final SeekableByteChannel channel = Files.newByteChannel(hugeFile, options);)

Solution 3

You can open the file for writing, seek to offset (n-1), and write a single byte. The OS will automatically extend the file to the desired number of bytes.

Benedikt Waldvogel

Comments

Is there an efficient way to create a file with a given size in Java? In C it can be done with ftruncate (see that answer). Most people would just write n dummy bytes into the file, but there must be a faster way. I’m thinking of ftruncate and also of Sparse files…

sk: In general, yes. In practice, this depends on the specifics of the underlying OS and might require some fiddling to make the file sparse.

Читайте также:  Html lock scroll lock

Jonathan Leffler

On Unix and Linux, that will be a sparse file — one block of zero bytes apart from the single byte written (which might also be zero, of course).

Sandeep Chauhan

In javadoc, it is written that «In this case, the contents of the extended portion of the file are not defined». Does this still guaranties to be zeroed on windows and linux, or is there any efficient way to be sure all bytes are zeros?

I would expect that any OS worth its salt (this includes Windows and Linux) to zero the bytes, to avoid the leakage of older data belonging to another user. However, I can think of scenarios where this would not be the case: old data belonging to the same process, or a small (J2ME) platform.

Interestingly RandomAccessFile.setLength() API also fills the file with zero’s which can be very useful at times.

@Sandeep that is not correct. The Javadoc specifically says that ‘the contents of the extended portion of the file are not defined’. The zeros may be the behaviour on a specific platform.

Does the above answer really work? The only thing created on my test system (a CentOS 5.6 VM) seems to be an EMPTY file that reports the «allocated» size via the length() method, which can be arbitrarily large, irrespective of available space. If you open the file and write a few characters, the file size changes to a few bytes. The getFreeSpace() method of the File class reports the same amount of available space before and after «creating» the file and you can use up the free disk space of the partition as if the created file was not there, irrespective of how large the preset length is.

Dana Robinson

A file of a given size, does not have to occupy that many bytes. Many systems support sparse files (this is what you are seeing), where parts of the file that are empty are not stored on disk. Other systems may support compressed files, where the amount of storage used depends on how compressible are the file’s contents.

talha06

Works as it is expected, but are there any ways to configure this approach to generate unique files (which MD5 values are different)? @DiomidisSpinellis

To make the files uniquely different create them with a different length, or tack a UUID at the beginning or at the end of the file.

The original question specifically asked about creating a sparse file. Sparse files by definition require less storage than their length.

Источник

Java – Create file with given size in Java

Is there an efficient way to create a file with a given size in Java?

In C it can be done with ftruncate (see that answer).

Most people would just write n dummy bytes into the file, but there must be a faster way. I’m thinking of ftruncate and also of Sparse files…

Best Solution

Create a new RandomAccessFile and call the setLength method, specifying the desired file length. The underlying JRE implementation should use the most efficient method available in your environment.

on a Linux machine will allocate the space using the ftruncate(2)

6070 open("t", O_RDWR|O_CREAT, 0666) = 4 6070 fstat(4, ) = 0 6070 lseek(4, 0, SEEK_CUR) = 0 6070 ftruncate(4, 1073741824) = 0 

while on a Solaris machine it will use the the F_FREESP64 function of the fcntl(2) system call.

/2: open64("t", O_RDWR|O_CREAT, 0666) = 14 /2: fstat64(14, 0xFE4FF810) = 0 /2: llseek(14, 0, SEEK_CUR) = 0 /2: fcntl(14, F_FREESP64, 0xFE4FF998) = 0 

In both cases this will result in the creation of a sparse file.

Java – Is Java “pass-by-reference” or “pass-by-value”

Java is always pass-by-value. Unfortunately, when we deal with objects we are really dealing with object-handles called references which are passed-by-value as well. This terminology and semantics easily confuse many beginners.

public static void main(String[] args) < Dog aDog = new Dog("Max"); Dog oldDog = aDog; // we pass the object to foo foo(aDog); // aDog variable is still pointing to the "Max" dog when foo(. ) returns aDog.getName().equals("Max"); // true aDog.getName().equals("Fifi"); // false aDog == oldDog; // true >public static void foo(Dog d) < d.getName().equals("Max"); // true // change d inside of foo() to point to a new Dog instance "Fifi" d = new Dog("Fifi"); d.getName().equals("Fifi"); // true >

In the example above aDog.getName() will still return «Max» . The value aDog within main is not changed in the function foo with the Dog «Fifi» as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return «Fifi» after the call to foo .

public static void main(String[] args) < Dog aDog = new Dog("Max"); Dog oldDog = aDog; foo(aDog); // when foo(. ) returns, the name of the dog has been changed to "Fifi" aDog.getName().equals("Fifi"); // true // but it is still the same dog: aDog == oldDog; // true >public static void foo(Dog d) < d.getName().equals("Max"); // true // this changes the name of d to be "Fifi" d.setName("Fifi"); >

In the above example, Fifi is the dog’s name after call to foo(aDog) because the object’s name was set inside of foo(. ) . Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog , but it is not possible to change the value of the variable aDog itself.

For more information on pass by reference and pass by value, consult the following SO answer: https://stackoverflow.com/a/430958/6005228. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.

Python – How to check whether a file exists without exceptions

If the reason you’re checking is so you can do something like if file_exists: open_it() , it’s safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.

If you’re not planning to open the file immediately, you can use os.path.isfile

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

import os.path os.path.isfile(fname) 

if you need to be sure it’s a file.

Starting with Python 3.4, the pathlib module offers an object-oriented approach (backported to pathlib2 in Python 2.7):

from pathlib import Path my_file = Path("/path/to/file") if my_file.is_file(): # file exists 
if my_file.is_dir(): # directory exists 

To check whether a Path object exists independently of whether is it a file or directory, use exists() :

if my_file.exists(): # path exists 

You can also use resolve(strict=True) in a try block:

try: my_abs_path = my_file.resolve(strict=True) except FileNotFoundError: # doesn't exist else: # exists 
Related Question

Источник

Make a file of desired size using java ?

send pies

posted 11 years ago

  • Report post to moderator
  • Please suggest some ways to make java code which generates a file of size entered by the user. The range can be from a few bytes (bits also possible . ) to many megabytes.
    Thanks.

    Java Cowboy

    Scala

    send pies

    posted 11 years ago

  • Report post to moderator
  • What data should the file contain, or does it not matter?

    You can just open a FileOutputStream and write as many bytes to it as is necessary. You cannot create a file with a fractional number of bytes (for example, a file with 4 bits).

    send pies

    posted 11 years ago

  • Report post to moderator
  • Jesper de Jong wrote: What data should the file contain, or does it not matter?

    Random characters. Does the code change according to the data that this file may contain ? Please give examples.

    Bartender

    send pies

    posted 11 years ago

  • Report post to moderator
  • It might depending on what you want to do. Just open one of many tutorials about I/O and see for yourself.

    «Any fool can write code that a computer can understand. Good programmers write code that humans can understand.» — Martin Fowler
    Please correct my English.

    Источник

    Оцените статью