(new File("filename")).delete();
Deleting a Directory
(new File("directoryName")).delete();
Creating a Temporary File
try {
// Create temp file.
File temp = File.createTempFile("pattern", ".suffix");
// Delete temp file when program exits.
temp.deleteOnExit();
// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("aString");
out.close();
} catch (IOException e) {
}
Using a Random Access File
try {
File f = new File("filename");
RandomAccessFile raf =
new RandomAccessFile(f, "rw");
char ch = raf.readChar();// Read a character.
raf.seek(f.length());// Seek to end of file.
raf.writeChars("aString"); // Append to the end.
raf.close();
}
catch (IOException e) {}
Serializing an Object
The object to be serialized must implement java.io.Serializable.
try
{
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(object);
out.close();
}
catch (IOException e) {}
Deserializing an Object
This example deserializes a java.awt.Button object.
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("filename.ser"));
AnObject object = (AnObject) in.readObject();
in.close();
} catch (ClassNotFoundException e)
{
} catch (IOException e) {}
Traversing a Directory
public static void traverse(File f)
{
process(f);
if (f.isDirectory())
{
String[] children = f.list();
{for (int i=0; i
traverse(new File(f, children[i]));
}
}
}
}
No comments:
Post a Comment