Tutorials Hut

Java File and IO Operations

Java file and IO have a lot of classes and methods to read and write files and do IO operations. Package named java.io contains these useful classes and methods.

Java File Class

In java class java.io.File is used to create files and also contains useful methods to check file or file system.

Java File Creation

Simple code to create file object for file named “testfile.txt”

import java.io.File;
public class FilesExample {
	public static void main(String[] args) {
    	File sampleFile = new File("testfile.txt");
 }
}

Methods in Java File Class

Below are very useful methods of file class.

  1. canRead() – Checks if file is readable or not and return boolean.
  2. canWrite() – Checks if file can be written or not and returns boolean.
  3. createNewFile() – Creates an empty file.
  4. exists() – Checks if file or directory exists or not.
  5. getName() – Returns name of file.
  6. length() – Returns size of file in bytes.
  7. getAbsolutePath() – Returns abs path of file.
  8. list() – Returns list of files in a file system or directory.
  9. mkdir() – Creates a directory.
  10. mkdirs() – Creates directory and parents of directoty as well.
  11. isDirectory() – Checks if file is a directory or not.
  12. delete() – Deletes the file.
  13. deleteOnExit() – This method request deletetion of file when java or JVM terminates, should be used carefully.
  14. getPath() – Returns path.

Java File Creation and Writing

In below example we will use File class to create a file and FileWriter to write a file.
File read write operation may raise exception related to file IO, so IOException class is used as well. See below program’s imports.

Example:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FilesExample {

public static void main(String[] args) throws IOException {
File sampleFile = new File("testfile.txt"); //Creates file
FileWriter fileWriter = new FileWriter("testfile.txt"); //Creates writer to write on above created file
fileWriter.write("Hello I am file, created by java file writer");
fileWriter.close();
}
}

Output:
A file will be created in current directory with name “testfile.txt” and content of file will be “Hello I am file, created by java file writer”

Java Read Files Using Scanner

In above examples we saw how to create and write a file, now let’s see how we can read a file.
We will use Scanner class to read a file.

Example:

import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FilesExample {
	public static void main(String[] args) throws IOException {
    	File sampleFile = new File("testfile.txt"); //Creates file
    	FileWriter fileWriter = new FileWriter("testfile.txt"); //Creates writer to write on above created file
    	fileWriter.write("Hello I am file, created by java file writer"); // write something to file
    	fileWriter.close();
    	//Scanner to read file
    	Scanner scanner = new Scanner(sampleFile);
    	while ((scanner.hasNext())){
        	System.out.println(scanner.nextLine());
    	}
	}
}

Output:

Hello I am file, created by java file writer

Directories in Java

Directories are nothing but folder in a computer in simple words. In java File class there are mkdir() and mkdirs() are useful methods to create directory.

Example Creating Directories:

import java.io.File;
public class FilesExample {
	public static void main(String[] args)  {
    	String dirName = "test";
    	File dir = new File(dirName);
    	dir.mkdir(); //this will create dir test
    	String dirName2 = "/abc/test";
    	File dir2 = new File(dirName2);
    	dir.mkdirs(); //this will create dir with parent dir as well
	}
}

Listing Directories and Files

File class has a list() method which lists all files and directories in a directory.

Example:

import java.io.File;
public class FilesExample {
	public static void main(String[] args)  {
    	String dirName = "test"; //this dir already exists with some file and sub dir
    	File dir = new File(dirName);
    	String[] dirArray = dir.list();
    	//print all files and paths
    	for(String name : dirArray){
        	System.out.println(name);
    	}
	}
}

Output:

dummy.txt
dummy

Java FileInputStream

FileInputStream is a java class used to read a file.
Example:
Below we have a file samplefile.txt and with help of FileInputStream we created an object to read stream of file.

File file = new File("samplefile.txt");
InputStream inputStream = new FileInputStream(file);

Methods in FileInputStream:

  1. public int read(int r)throws IOException{} – This is used to read specific byte of data from input stream.
  2. public int read(byte[] r) throws IOException{} – Another method to read data from stream.
  3. public void close() throws IOException{} – This method closes the stream and releases file and its access which may be needed by underlying OS.
  4. public int available() throws IOException{} – Returns number of bytes available from input stream.

Java FileOutputStream

FileOutputStream is a class which is used to write file.

Example:

File file = new File("samplefile.txt");
OutputStream outputStream = new FileOutputStream(file);

Methods in FileOutputStream

  1. public void write(int w)throws IOException{} – Writes data.
  2. public void write(byte[] w) – Writes byte data.
  3. public void close() throws IOException{} – Closes stream.

Example FileInputStream and FileOutputSteam

Below is a sample code which reads from one input file using FileInputStream and writes to another using FileOutputSteam.

import java.io.IOException;
public class FilesExample {
	public static void main(String[] args) throws IOException {
   	 FileInputStream fileInputStream = new FileInputStream("testfile.txt"); //reader input stream
    	FileOutputStream fileOutputStream = new FileOutputStream("testoutput.txt"); //writer inpur stream
    	int data;
    	while((data = fileInputStream.read()) != -1) {
        	fileOutputStream.write(data);
    	}
	}
}

Java File Delete

We can use file class delete() method to delete files and folders.

Example showing how to delete file and folder:

import java.io.File;



public class FilesExample {



	public static void main(String[] args)  {



    	//Below code will delete file

    	String fileName = "testfile.txt"; //dummy file

    	File file = new File(fileName);

    	file.delete();



    	//Below code will delete folder test

    	String dirName = "test"; //this dir already exists with some file and sub dir

    	File dir = new File(dirName);

    	dir.delete();



	}

}

Output:
Above code will delete file named “testfile.txt” and then delete folder (directory) named “test”.

References

Below are some of references from oracle official page on File and IO:

Next Article To Read

If you missed our previous article worth reading: Java Methods
Now, you may explore our next articles:














  • Leave a Reply

    Your email address will not be published. Required fields are marked *