File Handing in java comes under IO operations. Java IO package java.io
classes are specially provided for file handling in java.
File Handling in Java
Some of the common file handling operations are;
- Create file
- Delete file
- Read file
- Write file
- Change file permissions
Let’s look into each of these file handling operations through java program example.
Create File
We can use File class createNewFile()
method to create new file. This method returns true if file is successfully created, otherwise it returns false. Below is a simple program showing how to create a new file in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.journaldev.files; import java.io.File; import java.io.IOException; public class FileHandling { public static void main(String[] args) { File file = new File("data.txt"); try { boolean createNewFile = file.createNewFile(); System.out.println("File Created = "+createNewFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <img class="alignnone wp-image-30790 size-full" src="https://all-learning.com/wp-content/uploads/2016/10/file-handling-in-java-creates.png" alt="file-handling-in-java-create" width="1200" height="628" /> |
Above image shows the output produced in first run, in subsequent execution the file will be present so the createNewFile
will return false.
There are some rules associated with absolute path and relative path, read about them at java create new file.
Delete File
File class delete method is used to delete a file or an empty directory. Below is a simple example to delete a file.
1 2 3 4 5 6 7 8 9 10 11 |
package com.journaldev.files; import java.io.File; public class FileHandling { public static void main(String[] args) { File file = new File("data.txt"); boolean delete = file.delete(); System.out.println("File deleted = " + delete); } } |
File delete method returns true if file is deleted successfully or else it returns false.
Further Reading: Java delete file
Read File
There are many ways to read a file in java. We can use BufferedReader, FileReader or Files class. Below code snippet is to read file line by line.
1 2 3 4 5 6 7 8 9 10 11 12 |
File file = new File("data.txt"); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, cs); BufferedReader br = new BufferedReader(isr); String line; while((line = br.readLine()) != null){ //process the line System.out.println(line); } br.close(); |
For all other ways to read file, go to java read file.
Write File
We can use FileWriter, BufferedWriter, Files or FileOutputStream to write file in java. Below code snippet use Stream to write data to file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
OutputStream os = null; try { os = new FileOutputStream(new File("/Users/pankaj/os.txt")); os.write(data.getBytes(), 0, data.length()); } catch (IOException e) { e.printStackTrace(); }finally{ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } |
For a complete example with other classes, refer java write to file.
Change File Permissions
File class provide methods to get file permission details as well as change them. Below code snippet shows you how to read file permissions and change them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
File file = new File("/Users/pankaj/run.sh"); //check file permissions for application user System.out.println("File is readable? "+file.canRead()); System.out.println("File is writable? "+file.canWrite()); System.out.println("File is executable? "+file.canExecute()); //change file permissions for application user only file.setReadable(false); file.setWritable(false); file.setExecutable(false); //change file permissions for other users also file.setReadable(true, false); file.setWritable(true, false); file.setExecutable(true, true); |
However if you are using Java 7 or higher version, you should use PosixFilePermission
that provides more options.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//using PosixFilePermission to set file permissions 777 Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); Files.setPosixFilePermissions(Paths.get("/Users/pankaj/run.sh"), perms); |
Read more about PosixFilePermission
That’s all about file handling in java. I hope it will help you in getting started with file operations in java programs.