In order to work with files in java we need to first learn about the file class. The file class allows us to represent a file in our file system. Let’s Import java.io.* for all the necessary classes.
import java.io.*;
File file =new File("dummy.txt");
File file2= new File("/Dev/java/dummy.txt");
In the code above we create two file objects representing dummy.txt, one in the current directory and the other in a specified directory. Instantiating the file class doesn’t create the file!
//creates the file
file.createNewFile();
//delete the file
file.delete();
We can use the createNewFile() method to create the file if it doesn’t exist. Similarly, we can delete the file with the delete() if it exist. Note that these functions will return an IO exception if an error occurs and should be handled.
//check if file is a directory
if(!file.isDirectory())
System.out.println("Not a directory!")
String getFiles[]=file.list();
file object can also represent a directory, we can check if our file is a directory by calling isDirectory(), if true then we can get all the current files and directories with list(). List() method returns a string array.
Now that we know the basics of the file class, let’s learn how we can write to a file and read from one. In java, we have input and output streams that allows data to flow from a source and to a destination.
public static void writeFile() throws IOException{
//Set the output stream in order to write to the file "Output data to the file"
FileOutputStream out= new FileOutputStream("dummy.data");
//create a byte array
byte b[]= new byte[]{10,20,30};
//write the array to file
out.write(b);
System.out.println("wrote to file");
out.close();
}
To write to a file all we need to use is the FileOutputStream, which takes in a file. This opens up an output stream, we call the write() on the stream to write to the file. Close the stream when done using it. The FileOutputStream can only write bytes.
public static void readFile() throws IOException{
//Set the input stream in order to read from file "Input data from the file"
FileInputStream in= new FileInputStream("dummy.data");
//create a byte array
byte b[]= new byte[3];
//read from the file
in.read(b);
for(byte x: b)
System.out.print(x+" ");
in.close();
}
Similarly, we can read from a file by using a FileInputStream. We call the read(bytes b[]) this method takes in byte array and stores the data on the array. The FileInputStream can only read bytes.