How can I empty a file?

R

Ramon F Herrera

How can I accomplish something like this:

% cp /dev/null somefile

in Java??

Thanks,

-Ramon
 
V

Vincent van Beveren

How can I accomplish something like this:
% cp /dev/null somefile

in Java??

RandomAccessFile raf = new RandomAccessFile("somefile", "rw");
raf.setLength(0);
raf.close();

or

(new FileOutputStream("somefile")).close();

or

File f = new File("somefile");
if (f.exists()) {
f.delete();
}
f.createNewFile();

Vincent
 
R

Ramon F Herrera

Vincent said:
RandomAccessFile raf = new RandomAccessFile("somefile", "rw");
raf.setLength(0);
raf.close();

or

(new FileOutputStream("somefile")).close();

or

File f = new File("somefile");
if (f.exists()) {
f.delete();
}
f.createNewFile();

Vincent

Vince:

Thanks for your answer. I should have specified that the file
"somefile" already exists but I don't care about its contents, I just
need to empty it.

-Ramon
 
O

Oliver Wong

Ramon F Herrera said:
Vince:

Thanks for your answer. I should have specified that the file
"somefile" already exists but I don't care about its contents, I just
need to empty it.

Did you try the suggestions above? I think they would work despite this
extra specification.

- Oliver
 
R

Ramon F Herrera

Oliver said:
Did you try the suggestions above? I think they would work despite this
extra specification.

- Oliver

Yes, I tried them, and they work as expected.

Thanks!

-Ramon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top