JavaFAQ Home » General Java
Question: How can I open, read, write and close files in Java? Can I move, rename and delete file in Java? Examples? Can I filter files by file's extension?
Answer: Yes you can do all usual operations with files in Java: open, read, write, close, move, rename and delete.
You can even filter files by file's extension. All the file operations most easy to do in Java application. By default it is not for applets. If you try to open a file by applet you will get such or similar error (depends on Java version):
java.security.AccessControlException: access denied (java.io.FilePermission yourfilename read) at java.security.AccessControlContext.
checkPermission(AccessControlContext.java:270) at java.security.AccessController.
checkPermission(AccessController.java:401) at java.lang.SecurityManager.
checkPermission(SecurityManager.java:542) at java.lang.SecurityManager.
It is possible to open files with applet but user must explicitly permit it to Security manager (you write this functionality). So if you write a program which runs locally it is easier to write an application instead of applet.
File operations are often OS dependant. You code which works on Windows can stop to work on UNIX-like OS's due to higher security. Files which are in mounted directories (look like they are here on local file system, but are far away on the other side of network) also can cause many troubles.. So be ready to test all the cases if you write your code for different OS's and file systems.
During my latest work as Java programmer I collected a lot of useful examples for files related operations. They all working well and can give you good idea how to use file operations in Java.
By the way, I have more than 1000 Java examples on other areas of Java as well. My principle is: only working Java Code Examples. Some examples require few more classes, you can find them by powerful Java Code Search - supports boolean search, exact pattern and more.
So please take a look at File related code examples below:
You can also look at examples for FileReader, FileWriter, FileDescriptor, FileFilter, FilenameFilter, FileInputStream, FileOutputStream, FileNotFoundException
Printer Friendly Page
Send to a Friend
Search here again if you need more info!