27.04.2013 Views

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

File Systems I<br />

java.io.File.delete().<br />

Q: When creating a new file, is it possible to control whether or not an existing file<br />

with the same name is/is not overwritten? I haven't been able to answer this by<br />

looking at the java.io api<br />

Answer: There is a method in File to atomically create a new file which will fail if the<br />

file exists... You can use this to try creating the file, and if it exists already don't ever<br />

open the FileOutputStream to write contents.<br />

Q: Do exist Compound Files in <strong>Java</strong>?<br />

Microsoft has made an API where you can have a whole "virtual" filesystem inside a<br />

single file on the real filesystem. I think they call it Compound Files - I have also<br />

heard about the concept under the name of Structured Storage.<br />

Do any of you know if something like that exists in a <strong>Java</strong>-library? I have to work for<br />

all platforms! (It can of cause be implemented with the use of Compound Files in its<br />

Windows implementation)<br />

Answer: jar files are essentially the same.<br />

Have a look at java.util.jar.JarFile<br />

-by<br />

Bret Hansen<br />

Q: Is it possible to redirect the System.out.println to a file?<br />

Answer: Connect a PrintStream to the file, and then call System.setOut (PrintStream<br />

out) that reassigns the "standard" output stream.<br />

Q: Could some kind person please tell me how to save the object as a file so as<br />

the same program can load it again?<br />

Answer: try this program. It saves obect into file:<br />

import java.io.File;<br />

import java.io.FileOutputStream;<br />

import java.io.ObjectOutputStream;<br />

import java.io.IOException;<br />

public class Save{<br />

public void saveMyObject(String filename, Object obj) {<br />

File myFile = new File(filename);<br />

try {<br />

FileOutputStream fileOutStr = new FileOutputStream(myFile);<br />

ObjectOutputStream outStr = new ObjectOutputStream(fileOutStr);<br />

outStr.writeObject(obj);<br />

outStr.close();<br />

}catch (IOException e){<br />

System.out.println("?!!!!!!");<br />

}<br />

}<br />

public static void main (String args[]) {<br />

Save s = new Save();<br />

Object myObject = new Object();<br />

String test = "test";<br />

file:///F|/350_t/350_tips/filesystems-I.htm (2 of 4) [2002-02-27 21:17:56]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!