File Operations in Java
File operations plays an important role in java, Reading a file, renaming, deleting etc. In this article we are going to see some file operations,

  • Creating a file
  • Writing a content into that file
  • Reading the content from the file

Before we proceed to the coding, it is important for us to get familiar regarding some Input/Output methods

File – Used to create an object for file
FileReader – Used to read characters
BufferedReader – Enhances the filereader by reading a more data and storing it in buffer
FileWriter – Write characters to a file
BufferedWriter – Enhances filewriter by writing more data
PrintWriter – used for enhancement and has other methods than bufferedwriter

public class FileOperations {
    public static void main(String[] args) throws IOException 
            File file = new File("notes.txt");// creates an object for file notes.txt
            System.out.println(file.exists()); // checks if file already exists
            file.createNewFile(); // creates a new file with name "notes.txt"
            FileWriter fw = new FileWriter(file); // File Writer object for writing
            PrintWriter pw = new PrintWriter(fw); // Print Writer to enhance File Writer Operation
            pw.write("JavaInfinite - a website for Java Developers, new developers"); // writing
            FileReader fr = new FileReader(file); // File Reader to read the file
            BufferedReader br = new BufferedReader(fr); // Buffered Reader to enhance the reading
            String line="";
            while((line = br.readLine())!=null) // Read the data line by line

Please note that,

File file = new File(“notes.txt”); –> This does not create a new File, This just creates an object


By Sri

Leave a Reply

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