4. List Content of a Directory
8. Read and Set File Permissions
9. Getting Disk Drives Information
try { File file = new File("E:\\Java\\Test\\FileIO\\Code.java"); boolean created = file.createNewFile(); if (created) { System.out.println("The file has been created"); } } catch (IOException ex) { System.err.println(ex.getMessage()); }And to create a file on Linux-based operating systems, construct a file with the path like this:
File file = new File("/home/yourname/Java/Code.java");To create a file in the current directory (same as the current running program’s directory):
File file = new File("Code.java");You can use the constant File.separatorto construct a path name which is system-dependent and don’t worry about Linux or Windows, for example:
String userHomeDir = System.getProperty("user.home"); String path = userHomeDir + File.separator + "Code.java"; File file = new File(path); boolean created = file.createNewFile();
try { File tempFile = File.createTempFile("CodeJava", ".log"); BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); writer.write("I love Java"); writer.close(); } catch (IOException ex) { System.err.println(ex.getMessage()); }You will see a file whose name looks something like CodeJava6649987320877041676.log in the temporary directory.
File newDir = new File("CodeJava"); if (newDir.mkdir()) { System.out.println("Directory created"); } else { System.out.println("Directory not created"); }You can also use the mkdirs()method to create nested directories, for example:
File newDir = new File("CodeJava\\FileIO\\Examples"); if (newDir.mkdirs()) { System.out.println("Directories created"); } else { System.out.println("Directories not created"); }This creates three nested directories in the current directory: CodeJava\FileIO\Examples.
File userHomeDir = new File(System.getProperty("user.home")); String[] content = userHomeDir.list(); for (String entry : content) { System.out.println(entry); }This prints the content of the user’s home directory.You can supply a FilenameFilter to another overload of the list() method to list only files and directories that satisfy a condition. For example, the following code lists only .java files in the current directory:
File currentDir = new File("."); FilenameFilter filter = new FilenameFilter() { public boolean accept(File file, String name) { return name.endsWith(".java"); } }; String[] content = currentDir.list(filter); for (String entry : content) { System.out.println(entry); }Similarly, the methods listFiles() and listFiles(FilenameFilter)do the same, but return an array of File objects.For more examples about listing a directory (including listing recursively), see this article: How to list files and directories in a directory.
File oldName = new File("CodeJavaLogoBig.png"); File newName = new File("CodeJavaLogoSmall.png"); boolean renamed = oldName.renameTo(newName); if (renamed) { System.out.println("The file was renamed"); } else { System.out.println("Could not rename"); }This renames the file CodeJavaLogoBig.png to CodeJavaLogoSmall.png. You can use this method to move a file or directory to another location, however it is platform-dependent, which means it may work on this operating system but not on others.
File file = new File("CodeJavaLogoSmall.png"); if (file.delete()) { System.out.println("The file was deleted"); } else { System.out.println("Could not delete the file"); }To delete a non-empty directory, you must delete all the files and sub directories within it. See: Clean and remove a non-empty directory.You can invoke the deleteOnExit() method to tell the Java Virtual Machine deletes the file when the program exits and the JVM terminates. This is useful for deleting temporary files used by a program.
File file = new File("CodeJavaLogoSmall2.png"); boolean existed = file.exists(); String absolutePath = file.getAbsolutePath(); String name = file.getName(); String parent = file.getParent(); File parentFile = file.getParentFile(); boolean isDirectory = file.isDirectory(); boolean isFile = file.isFile(); boolean isHidden = file.isHidden(); Date lastModified = new Date(file.lastModified()); long size = file.length(); System.out.println("Existed? " + existed); System.out.println("Absolute Path = " + absolutePath); System.out.println("Name = " + name); System.out.println("Parent = " + parent); System.out.println("Parent File = " + parentFile); System.out.println("Is Directory = " + isDirectory); System.out.println("Is File = " + isFile); System.out.println("Is Hidden = " + isHidden); System.out.println("Last Modified = " + lastModified); System.out.println("Size = " + size);
File file = new File("CodeJavaLogoSmall.png"); if (file.canWrite()) { if (file.setReadOnly()) { System.out.println("The file was set to read-only"); } }In addition, you can use the setLastModified() method to set the last-modified time of a file or directory, for example:
File file = new File("CodeJavaLogoSmall.png"); long currentTime = System.currentTimeMillis(); if (file.setLastModified(currentTime)) { System.out.println("File's last-modified was updated"); }This sets the last-modified time of the file to the current time.
File[] drives = File.listRoots(); if (drives != null && drives.length > 0) { for (File aDrive : drives) { System.out.println("Drive Letter: " + aDrive); System.out.println("\tTotal space: " + aDrive.getTotalSpace()); System.out.println("\tFree space: " + aDrive.getFreeSpace()); System.out.println(); } }And here’s the output on my computer:
Drive Letter: C:\ Total space: 73402363904 Free space: 7710081024 Drive Letter: D:\ Total space: 106151542272 Free space: 5106290688
try ( BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(inputFile)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); ) { int byteRead; while ((byteRead = inputStream.read()) != -1) { outputStream.write(byteRead); } } catch (IOException ex) { ex.printStackTrace(); }However the above code is not efficient. Instead, you can use the FileChannel in the java.nio.channels package to copy a file more efficiently. The following method copies a source file to destination one using the FileChannel:
public static void copyFile(File sourceFile, File destFile) { try ( FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel destChannel = new FileOutputStream(destFile).getChannel(); ) { sourceChannel.transferTo(0, sourceChannel.size(), destChannel); } catch (IOException ex) { System.err.println(ex.getMessage()); } }To copy a whole directory recursively, see this example: How to copy a directory programmatically in Java