java.io.Serializable
. This example serializes a javax.swing.JButton
object.
See also e45 Deserializing an Object.
Object object = new javax.swing.JButton("push me"); try { // Serialize to a file ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser")); out.writeObject(object); out.close(); // Serialize to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream() ; out = new ObjectOutputStream(bos) ; out.writeObject(object); out.close(); // Get the bytes of the serialized object byte[] buf = bos.toByteArray(); } catch (IOException e) { }
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
File file = new File("filename"); // Get the last modified time long modifiedTime = file.lastModified(); // 0L is returned if the file does not exist // Set the last modified time long newModifiedTime = System.currentTimeMillis(); boolean success = file.setLastModified(newModifiedTime); if (!success) { // operation failed. }
FileDescriptor.sync()
blocks until all changes to a file are written to disk.
try { // Open or create the output file FileOutputStream os = new FileOutputStream("outfilename"); FileDescriptor fd = os.getFD(); // Write some data to the stream byte[] data = new byte[]{(byte)0xCA, (byte)0xFE, (byte)0xBA, (byte)0xBE}; os.write(data); // Flush the data from the streams and writers into system buffers. // The data may or may not be written to disk. os.flush(); // Block until the system buffers have been written to disk. // After this method returns, the data is guaranteed to have // been written to disk. fd.sync(); } catch (IOException e) { }
// Copies src file to dst file. // If the dst file does not exist, it is created void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); }
.
' or `..
' or symbolic links (on UNIX platforms). File.getCanonicalFile()
converts a filename path to a unique canonical form suitable for comparisons.
File file1 = new File("./filename"); File file2 = new File("filename"); // Filename paths are not equal boolean b = file1.equals(file2); // false // Normalize the paths try { file1 = file1.getCanonicalFile(); // c:\almanac1.4\filename file2 = file2.getCanonicalFile(); // c:\almanac1.4\filename } catch (IOException e) { } // Filename paths are now equal b = file1.equals(file2); // true
File
object is used to represent a filename. Creating the File
object has no effect on the file system; the filename need not exist nor is it created.
On Windows, this example creates the path\a\b
. On Unix, the path would be /a/b
.
String path = File.separator + "a" + File.separator + "b";
// Process all files and directories under dir public static void visitAllDirsAndFiles(File dir) { process(dir); if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i<children.length; i++) { visitAllDirsAndFiles(new File(dir, children[i])); } } } // Process only directories under dir public static void visitAllDirs(File dir) { if (dir.isDirectory()) { process(dir); String[] children = dir.list(); for (int i=0; i<children.length; i++) { visitAllDirs(new File(dir, children[i])); } } } // Process only files under dir public static void visitAllFiles(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i<children.length; i++) { visitAllFiles(new File(dir, children[i])); } } else { process(dir); } }
File dir = new File("directoryName"); String[] children = dir.list(); if (children == null) { // Either dir does not exist or is not a directory } else { for (int i=0; i<children.length; i++) { // Get filename of file or directory String filename = children[i]; } } // It is also possible to filter the list of returned files. // This example does not return any files that start with `.'. FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return !name.startsWith("."); } }; children = dir.list(filter); // The list of files can also be retrieved as File objects File[] files = dir.listFiles(); // This filter only returns directories FileFilter fileFilter = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; files = dir.listFiles(fileFilter);
java
command was invoked.
String curDir = System.getProperty("user.dir");