Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java read Files

Read a File

In the preceding chapter, you acquired the skills to generate and append data to a file.

In the forthcoming example, we utilize the Scanner class to retrieve the contents of the text file generated in the previous chapter.

Example

import java.io.File;  // Import the File class
import java.io.FileNotFoundException;  // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public class ReadFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      Scanner myReader = new Scanner(myObj);
      while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
        System.out.println(data);
      }
      myReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

The expected output is:

Files in Java might be tricky, but it is
fun enough!

Get File Information

For further details about a file, utilize any of the available File methods.

Example

import java.io.File;  // Import the File class
public class GetFileInfo { 
  public static void main(String[] args) {
    File myObj = new File("filename.txt");
    if (myObj.exists()) {
      System.out.println("File name: " + myObj.getName());
      System.out.println("Absolute path: " + myObj.getAbsolutePath());
      System.out.println("Writeable: " + myObj.canWrite());
      System.out.println("Readable " + myObj.canRead());
      System.out.println("File size in bytes " + myObj.length());
    } else {
      System.out.println("The file does not exist.");
    }
  }
}

The expected output is:

File name: filename.txt
Absolute
path: C:\Users\MyName\filename.txt

Writeable:
true

Readable:
true

File size
in bytes: 0

 

Note: The Java API offers many classes for reading and writing files, including FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, and FileOutputStream. The choice of class depends on your Java version, whether you need to read bytes or characters, and the file size or line length.

Tip: For information on deleting a file, refer to our Java Delete Files chapter.