Kensoft PH
  • Download
    • KenshotApplication
  • Contact
  • About
Java Quiz
No Result
View All Result
Kensoft PH
  • Download
    • KenshotApplication
  • Contact
  • About
Java Quiz
No Result
View All Result
Kensoft PH
No Result
View All Result
Home Java

How to read file in Java | 100% Perfect for beginners

February 19, 2022
in Java
Reading Time: 5 mins read
0
Read file in Java
291
VIEWS
Share on FacebookShare on TwitterShare via Email

In this article, I will show you how to read file in Java, as well as list and explain all of the possible methods so that you can understand and learn it easily. This is perfect for beginners like you.

File handling is important and useful for all developers, and you should be familiar with it in Java. In this tutorial, let’s talk about reading a file in Java. File handling is not only for reading a file but also to create and delete a file using the Java programming language. Remember, I will only discuss reading a file in Java in this topic.

Contents

Toggle
  • How to read file in Java
    • Scanner class
      • Example:
      • Output
    • BufferedReader class
      • Example
      • Output
    • FileReader class
      • Example
      • Output
  • How to get file information in Java
    • Example
    • Output

How to read file in Java

To read file in Java, we will use the Scanner class, BufferedReader class, and the FileReader class. To understand more about each method, read the descriptions below, and let’s start with the:

Scanner class

The Scanner class is available in the java.util package and if you want to use it, you need to import it. Using the Scanner to read a file in Java is very easy, even for beginners. We can parse the file and display it in our Java program using the Scanner class and you should be aware that the Scanner class is not ideal for reading passwords because it is publicly visible. Below are the methods of the Scanner class for scanning specific words or numbers. It is also useful to read file in Java.

  • Scanner (InputStream in) – This generate a scanner object from the given input stream.
  • String nextLine() – This method reads the next line of input.
  • String next() – This method reads the next word of input.
  • int nextInt() – This method reads the input that represents an integer.
  • double nextDouble() – This method reads the input that represents a floating-point number.
  • boolean hasNext() – This method will identify if there is another word in the input.
  • boolean hasNextInt() – This method will identify if there is another character that represents an integer.
  • boolean hasNextDouble() – This method will identify if there is another character that represents an floating-point number.

Now, to read file in Java using the Scanner please follow the given example below.

How to read file in Java

Example:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 *
 * @author KENSOFT
 */
public class ReadFile {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Reading file using Scanner
        try {
            File file = new File("C:\\Users\\KENSOFT\\Desktop\\kensoft.txt");
            Scanner scan = new Scanner(file);
            while(scan.hasNextLine()){
                System.out.println(scan.nextLine());
            }
        } catch (FileNotFoundException e) {
            System.out.println(e);
        }
    }
}

Output

Learn more at KENSOFTPH.COM

BufferedReader class

One of the most easiest ways to read file in Java is to use the BufferedReader class. The BufferedReader class allows you to read characters, arrays, and lines quickly and efficiently. Wrapping a BufferedReader around any reader whose read() method operations is recommended when using the BufferedReader. Consider the following example BufferedReader br = new BufferedReader(new FileReader(file));.That’s how you make a BufferedReader object in Java. Below are the methods of the BufferedReader class for reading characters. It is also useful to read file in Java.

  • close() – This method will close the stream and any system resources with it.
  • lines() – This method returns a stream which are the lines read from the BufferedReader.
  • mark(int readAheadLimit) – This method marks the present position in the stream.
  • markSupported() – This method will identify if the stream supports the mark() method.
  • read() – This method will read a single character.
  • readLine() – This method will read a line of text.
  • ready() – This method will identify if the stream is ready to be read.
  • reset() – This method will reset the stream.
  • skip(long n) – This method will skip characters

To learn how to read a file in Java using the BufferedReader class, please continue reading below.

Read file in Java

Example

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 *
 * @author KENSOFT
 */
public class ReadFile {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Reading file using BufferedReader
        try {
            File file = new File("C:\\Users\\KENSOFT\\Desktop\\kensoft.txt");
            BufferedReader br = new BufferedReader(new FileReader(file));
            String data;
            while((data = br.readLine()) != null){
                System.out.println(data);
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

Output

Learn more at KENSOFTPH.COM

FileReader class

The FileReader class is one of the most basic classes in Java for reading files. It is convenient for reading character files. FileReader class is meant for reading streams of characters in Java. The constructors for the FileReader class are listed below.

Constructor Detail

These are the constructors and its descriptions in the FileReader class.

  • FileReader( File file ) – This constructor generates a new FileReader to read from the specified file.
  • FileReader( FileDescriptor fd ) – This constructor generate a new FileReader to read from the FileDescriptor.
  • FileReader( String fileName ) – This constructor generates a new FileReader to read from the specified file name.

Please check the example below for how to read file in Java using the FileReader class.

How to read file in Java

Example

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author KENSOFT
 */
public class ReadFile {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Reading file using FileReader class
        try {
            FileReader fr = new FileReader("C:\\Users\\KENSOFT\\Desktop\\kensoft.txt");
            int data;
            while((data = fr.read()) != -1){
                System.out.print((char)data);
            }
        } catch (FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException ex) {
            Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Output

Learn more at KENSOFTPH.COM

How to get file information in Java

To get the file information in Java, we will use the File method. The information we are going to get from the file are these: File name, Absolute path, Writeable, Readable, and the File size. It is also part on how to read file in Java. To do this, take a look at the example provided below.

Example

import java.io.File;

/**
 *
 * @author KENSOFT
 */
public class ReadFile {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Get the file information
        File file = new File("C:\\Users\\KENSOFT\\Desktop\\kensoft.txt");
        if (file.exists()) {
            System.out.println("File name: " + file.getName());
            System.out.println("Absolute path: " + file.getAbsolutePath());
            System.out.println("Writeable: " + file.canWrite());
            System.out.println("Readable " + file.canRead());
            System.out.println("File size in bytes " + file.length());
        } else {
            System.out.println("The file does not exist.");
        }
    }
}

Output

File name: kensoft.txt
Absolute path: C:\Users\KENSOFT\Desktop\kensoft.txt
Writeable: true
Readable true
File size in bytes 38

To read file in Java is very easy, I hope you find this tutorial useful and helpful.

Previous Post

Comments in Java | 100% Perfect for beginner

Next Post

Working with layout in JavaFX | 100% Perfect for beginners

KENSOFT

KENSOFT

What’s up! Kent is my name. The name KENSOFT is derived from the words Kent and Software. My programming language of choice is Java

Related tutorials

How to Use the JavaFX Pie Chart 100% For Beginners
Java

How to Use the JavaFX Pie Chart 100% For Beginners

June 12, 2024 - Updated on October 6, 2024
205
How to Connect to an API Using JavaFX
Java

How to Connect to an API Using JavaFX

May 26, 2024 - Updated on September 28, 2024
215
JavaFX SQLite Database CRUD Tutorial
Java

JavaFX SQLite Database CRUD Tutorial | Note Application

May 26, 2024 - Updated on September 28, 2024
586
Next Post
Layout in JavaFX

Working with layout in JavaFX | 100% Perfect for beginners

How to open a URL in Java

How to open a URL in Java | 100% Perfect for Beginners

Layout in JavaFX

How to use the Group in JavaFX| 100% Perfect for beginners

Leave a Reply Cancel reply

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

Tools

Multi-platform installer builder

Java profiler

  • Trending
  • Comments
  • Latest
MySQL database using XAMPP

How to connect Java to MySQL database using Xampp server | 100% best for beginners

October 27, 2020 - Updated on January 23, 2023
Failed to automatically set up a JavaFX Platform

Failed to automatically set up a JavaFX Platform SOLVED Apache NetBeans 12.3 | Best way

April 11, 2021 - Updated on July 3, 2022
JavaFX 17

How To install JDK 17 and JavaFX 17 on NetBeans IDE | Best

November 15, 2021 - Updated on December 13, 2021
hide and show password in jPasswordField

JPasswordField in Java Hide or Show Password | 100% best for beginners

April 2, 2021 - Updated on September 21, 2022
Failed to automatically set up a JavaFX Platform

Failed to automatically set up a JavaFX Platform SOLVED Apache NetBeans 12.3 | Best way

3DES in Java and AES in Java

How to use AES and 3DES in Java | 100% best for beginners

JavaFX Splash Screen

How to create JavaFX Splash Screen | 100% best for beginners

set up JavaFX and Scene Builder

How to set up JavaFX and Scene Builder in NetBeans IDE | 100% best for beginners

How to Use the JavaFX Pie Chart 100% For Beginners

How to Use the JavaFX Pie Chart 100% For Beginners

June 12, 2024 - Updated on October 6, 2024
How to Connect to an API Using JavaFX

How to Connect to an API Using JavaFX

May 26, 2024 - Updated on September 28, 2024
JavaFX SQLite Database CRUD Tutorial

JavaFX SQLite Database CRUD Tutorial | Note Application

May 26, 2024 - Updated on September 28, 2024
How to take a screenshot on PC using Kenshot

How to Take a Screenshot on PC Using Kenshot: A Full Guide

January 18, 2024 - Updated on October 6, 2024

Latest Tutorials

How to Use the JavaFX Pie Chart 100% For Beginners

How to Use the JavaFX Pie Chart 100% For Beginners

June 12, 2024 - Updated on October 6, 2024
How to Connect to an API Using JavaFX

How to Connect to an API Using JavaFX

May 26, 2024 - Updated on September 28, 2024
JavaFX SQLite Database CRUD Tutorial

JavaFX SQLite Database CRUD Tutorial | Note Application

May 26, 2024 - Updated on September 28, 2024

Popular Tutorials

  • MySQL database using XAMPP

    How to connect Java to MySQL database using Xampp server | 100% best for beginners

    0 shares
    Share 0 Tweet 0
  • Failed to automatically set up a JavaFX Platform SOLVED Apache NetBeans 12.3 | Best way

    0 shares
    Share 0 Tweet 0
  • How To install JDK 17 and JavaFX 17 on NetBeans IDE | Best

    0 shares
    Share 0 Tweet 0
Facebook Instagram Youtube Github LinkedIn Discord
Kensoft PH

What’s up! I'm Kent. The name KENSOFT is derived from the words Kent and Software. My programming language of choice is Java, which I use to create computer applications. In a company, I created applications and a website.

Categories

Website

Check the status

Privacy Policy

Terms and Condition

Sitemap

Latest Tutorials

How to Use the JavaFX Pie Chart 100% For Beginners

How to Use the JavaFX Pie Chart 100% For Beginners

June 12, 2024 - Updated on October 6, 2024
How to Connect to an API Using JavaFX

How to Connect to an API Using JavaFX

May 26, 2024 - Updated on September 28, 2024
JavaFX SQLite Database CRUD Tutorial

JavaFX SQLite Database CRUD Tutorial | Note Application

May 26, 2024 - Updated on September 28, 2024

© 2024 Made With Love By KENSOFT PH

No Result
View All Result
  • Download
    • Kenshot
  • Contact
  • About
  • Java Quiz

© 2024 Made With Love By KENSOFT PH

This website uses cookies. By continuing to use this website you are giving consent to cookies being used. Visit our Privacy and Cookie Policy.