Java reading file using scanner

Java read file using 5+ methods [Easy Examples]

Introduction to Java read file using various methods

A file is a container in a computer system for storing information. Files used in computers are similar in features to that of paper documents used in library and office files. There are different types of files such as text files, data files, directory files, binary and graphic files, and these different types of files store different types of information. Different programming languages provide us different operations to be performed on these files.

In java, we can create, read and write on files using various. If you want to learn how to create and write on file in java then you can follow Java create & write to file Examples [Multiple Methods]

In this article, we will learn how we can read a file in java using various methods including Java desktop, FileInputStream , BufferedReader , FileReader , and Scanner class. All in all, this tutorial will contain all the necessary information and examples that you need to learn in order to start working with files in java.

Читайте также:  Kotlin json parse list

Different methods to read file in Java with Examples

As we already discussed the file is like a container that stores information and can be used later. In this section, we will look at various methods to read files. In this tutorial, we assume that our file name, » MyFile.txt » contains the following data.

java read file!! Welcome to golinuxclould!

Now let us apply different methods to read the existing file that contains the above data.

Method-1: Java read file using Java desktop class

The first method that we will use to read or open a file in java is the Desktop class. This class is present in the java.awt package. It has the method called open() that opens a file for us. As the Desktop is platform-independent, so we need to check whether our Operating System supports Desktop or not. If any error occurs, there arises an exception called FileNotFounDException .

Now let us take an example and open our file named «MyFile.txt». See the example below:

// importing desktop import java.awt.Desktop; // importing java io import java.io. * ; // main class public class Main < public static void main(String[] args) < try < //constructor of file class // java read file File myFile = new File("Myfile.txt"); // using if statment if (!Desktop.isDesktopSupported()) //check if Desktop is supported by Platform or not < System.out.println("This is not supported by platform!"); return; >Desktop desktop = Desktop.getDesktop(); // checking if file exists or not if (myFile.exists()) // Opens the file desktop.open(myFile); > // catch block to handle any kind of errors catch(Exception e) < System.out.println("Error accurs"); >> > 

If we run the following code, It will open the file in the text editor as shown below:

Читайте также:  Тип данных элементов массива python

Java read file using 5+ methods [Easy Examples]

This method can return different kinds of errors.

For example. NullPointer Exception if the file is null, IllegalArgumentException if the given file does not exist and UnsupportedOperationExecution if the platform does not support the Desktop. That is why it is always recommended to use try and catch blocks to handle any kind of exceptions.

You can read more about try and catch blocks from the article java try and catch blocks.

Method-2: Java read file using FileInputStream class

Another method to read files from a system using the java programming language is FileInputStream which reads input bytes from a file in a file system. Before using it, first, we have to import FileInputStream class. See the example below which uses this method to read the file.

// imporiting fileinputstream import java.io.FileInputStream; // main class public class Main < // main method public static void main(String args[])< //try block try< // constructor in fileinputstream class // java read file FileInputStream myfile=new FileInputStream("Myfile.txt"); // printing System.out.println("The file contains the followng data:"); // counter int counter = 0; // while loop to iterate while ((counter = myfile.read()) != -1) < System.out.print((char) counter); >// catch block to hadle the error >catch(Exception e) < System.out.println("Error accurs!"); >> >
The file contains the following data: java read file!! Welcome to golinuxclould!

Notice that this method does not open the file in any other external software, In fact, it reads the data and prints out the data.

Method-3: Java read file using BufferedReader Class

Now let us take another method which is BufferedReader class. The BufferedReader class can also use to read and open a file in Java. It reads the text using a character input stream and is present in the java.io package. Let us take the example and see how we can read files. See the program below:

// importing io import java.io. * ; // main class public class Main < // main method public static void main(String args[]) < try < //constructor of File class // java read file File myfile = new File("Myfile.txt"); //creates a buffer reader input stream BufferedReader newfile = new BufferedReader(new FileReader(myfile)); System.out.println("The file contains the following data: "); // counter int counter = 0; // while loop to iterate while ((counter = newfile.read()) != -1) < // java read file System.out.print((char) counter); >> catch(Exception e) < System.out.println("error occurs!"); >> >
The file contains the following data: java read file!! Welcome to golinuxclould!

Notice that this method prints all the data from the file using the while loop and iterating over the file unless it prints all the data in it. You can read more about the working principle of the while loop from the article Java while loop.

Method-4: Java read file using FileReader class

Another simple method to read a java file is using FileReader class, which is present in the java.io package. It reads bytes from FileInputStream class. Let us take an example and read a file and print out all the data. See the program below:

// importing io import java.io. * ; // main class public class Main < // main method public static void main(String args[]) < // try block try < //constructor of the File class // Java read file FileReader myfile = new FileReader("Myfile.txt"); // printing System.out.println("The file contains the following data: "); // counter int counter = 0; // while loop to iterate while ((counter = myfile.read()) != -1) < // java read file System.out.print((char) counter); >> catch(Exception e) < System.out.println("Error occurs!!"); >> >
The file contains the following data: java read file!! Welcome to golinuxclould!

Notice that this method reads the file and then again uses the while loop to iterate over the data and prints out all.

Method-5: Java read file using Scanner class

The Scanner class of java.util package is also useful in reading and opening a file in Java. Java Scanner class can parse the text using regular expressions. It breaks the input on the delimiter’s pattern. By default the delimiter is whitespace, but we can also add our own delimiter. We use the constructor of the Scanner class for opening and reading a file. To understand the process more clearly, See the example below:

// importing file import java.io.File; // importing scanner import java.util.Scanner; // java main class public class Main < // java main method public static void main(String[] args) < // try block try < // Stroing file // java read file File file = new File("Myfile.txt"); // File to be scanned Scanner myfile = new Scanner(file); System.out.println("The file contains the following data:"); // while loop to iterate while (myfile.hasNextLine()) //printing the data System.out.println(myfile.nextLine()); >catch(Exception e) < System.out.println("Error occurs!!");; >> >
The file contains the following data: java read file!! Welcome to golinuxclould!

Notice that we successfully read and print the data from a file.

Method-6: Java read file using NIO package

The Java NIO package has many classes and methods that use to read and open a file in Java but here we will discuss readAllLines() method. The readAllLines() method is the method that belongs to the File class.

This method is widely used to read all the lines from a file and decode the bytes from the file into characters using UTF-8 charset. This method returns the lines from the file in the form of a list.

Now, let us take an example and read one file using this mehod. See the example below:

// importing util import java.util. * ; // importing standardCharsets import java.nio.charset.StandardCharsets; // importing file import java.nio.file. * ; // importing io import java.io. * ; // java main class public class Main < // java readfile method // return type is list public static List < String >readFile(String fileName) < // create list using collections library List < String >lines = Collections.emptyList(); // try block try < // java read file lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8); >// catch block to handle exception catch(IOException e) < System.out.println("Error occurs!"); >// return lines of data return lines; > // main method public static void main(String[] args) < System.out.println("The file containg the following data:"); // java read file List mylist = readFile("Myfile.txt"); // accessing the elements by calling the method Iterator < String >itr = mylist.iterator(); // while loop to iterate while (itr.hasNext()) // print System.out.println(itr.next()); > >
The file containg the following data: java read file!! Welcome to golinuxclould!

Notice that we successfully read the file and then print all the data using readAllLines() method.

Summary

A file is a container in a computer system that stores data, information, settings, or commands, which are used with a computer program. Files play important role in any programming language because they can store a large amount of data. We can create, write and read files in java using different methods. In this article, we learned about java read files by taking various methods.

For example, we learned about Desktop class, FileInputStream , BufferedReader , FileReader , Scanner, and readAllLines() methods by taking different examples. In a conclusion, this tutorial contains all the important methods and classes that are used to read java files.

Further Reading

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment Cancel reply

Java Tutorial

  • Set Up Java Environment
    • Set Up Java on Linux
    • Set up Java with BlueJ IDE
    • Set up Java with VSC IDE
    • Set up Java with Eclipse IDE
    • Java Multiline Comments
    • Java Variables
    • Java Global Variables
    • Java Date & Time Format
    • Different Java Data Types
    • Java Booleans
    • Java Strings
    • Java Array
    • Java Byte
    • Java convert list to map
    • Java convert double to string
    • Java convert String to Date
    • Java convert Set to List
    • Java convert char to int
    • Java convert long to string
    • Java Operators Introduction
    • Java Boolean Operators
    • Java Relational Operators
    • Java Arithmetic Operators
    • Java Bitwise Operators
    • Java Unary Operators
    • Java Logical Operators
    • Java XOR (^) Operator
    • Java Switch Statement
    • Java If Else Statement
    • Java While Loop
    • Java For / For Each Loop
    • Java Break Continue
    • Java Nested Loops
    • Java throw exception
    • Java Try Catch
    • Java Accessor and Mutator Methods
    • Java main() Method
    • IndexOf() Java Method
    • Java ListIterator() Method
    • Java create & write to file
    • Java read file
    • Java Parameter
    • Java Argument
    • Java Optional Parameters
    • Java Arguments vs Parameters
    • Java Arrays.asList
    • Java HashSet
    • Java Math
    • Java HashMap vs Hashtable vs HashSet
    • Java LinkedList
    • Linked List Cycle
    • Java List vs LinkedList
    • Java ArrayList vs LinkedList

    Источник

    How to read file in Java using Scanner Example — text files

    From Java 5 onwards java.util.Scanner class can be used to read file in Java. Earlier we have seen examples of reading file in Java using FileInputStream and reading file line by line using BufferedInputStream and in this Java tutorial, we will See How can we use Scanner to read files in Java. Scanner is a utility class in java.util package and provides several convenient methods to read int , long , String , double etc from a source which can be an InputStream, a file, or a String itself.

    As noted on How to get input from User, Scanner is also an easy way to read user input using System.in (InputStream) as the source. The main advantage of using Scanner for reading files is that it allows you to change delimiter using the useDelimiter() method, So you can use any other delimiter like comma, pipe instead of white space.

    How to Read File in Java — Scanner Example

    In this Java program, we have used java.util.Scanner to read file line by line in Java. We have first created a File instance to represent a text file in Java and then we passed this File instance to java.util.Scanner for scanning.

    The scanner provides methods like hasNextLine() and readNextLine() which can be used to read file line by line. It’s advised to check for next line before reading next the line to avoid NoSuchElementException in Java.

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

    /**
    *
    * Java program to read files using Scanner class in Java.
    * java.util.Scanner is added on Java 5 and offers a convenient method to read data
    *
    * @author
    */
    public class ScannerExample

    public static void main ( String args []) throws FileNotFoundException

    //creating File instance to reference text file in Java
    File text = new File ( «C:/temp/test.txt» ) ;

    //Creating Scanner instance to read File in Java
    Scanner scnr = new Scanner ( text ) ;

    //Reading each line of the file using Scanner class
    int lineNumber = 1 ;
    while ( scnr. hasNextLine ()) <
    String line = scnr. nextLine () ;
    System. out . println ( «line » + lineNumber + » :» + line ) ;
    lineNumber++ ;
    >

    Output:
    line 1 :——————— START——
    ————————————————
    line 2 :Java provides several way to read files.
    line 3 :You can read file using Scanner, FileReader,
    FileInputStream and BufferedReader.
    line 4 :This Java program shows How to read file using java. util .Scanner class .
    line 5 :——————— END————————
    ———————————

    This is the content of test.txt file exception line numbers. You see it doesn’t require much coding to read file in Java using Scanner . You just need to create an instance of Scanner and you are ready to read file.

    Источник

Оцените статью