Examples of reading files in java

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.

Читайте также:  Html adaptive images with

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 start program windows

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

    Источник

    Examples of reading files in java

    • Introduction to Java
    • The complete History of Java Programming Language
    • C++ vs Java vs Python
    • How to Download and Install Java for 64 bit machine?
    • Setting up the environment in Java
    • How to Download and Install Eclipse on Windows?
    • JDK in Java
    • How JVM Works – JVM Architecture?
    • Differences between JDK, JRE and JVM
    • Just In Time Compiler
    • Difference between JIT and JVM in Java
    • Difference between Byte Code and Machine Code
    • How is Java platform independent?
    • Decision Making in Java (if, if-else, switch, break, continue, jump)
    • Java if statement with Examples
    • Java if-else
    • Java if-else-if ladder with Examples
    • Loops in Java
    • For Loop in Java
    • Java while loop with Examples
    • Java do-while loop with Examples
    • For-each loop in Java
    • Continue Statement in Java
    • Break statement in Java
    • Usage of Break keyword in Java
    • return keyword in Java
    • Object Oriented Programming (OOPs) Concept in Java
    • Why Java is not a purely Object-Oriented Language?
    • Classes and Objects in Java
    • Naming Conventions in Java
    • Java Methods
    • Access Modifiers in Java
    • Java Constructors
    • Four Main Object Oriented Programming Concepts of Java
    • Inheritance in Java
    • Abstraction in Java
    • Encapsulation in Java
    • Polymorphism in Java
    • Interfaces in Java
    • ‘this’ reference in Java

    Источник

    Java Read Files

    In the previous chapter, you learned how to create and write to a file.

    In the following example, we use the Scanner class to read the contents of the text file we created 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(); >> > 

    Get File Information

    To get more information about a file, use any of the 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."); >> >

    File name: filename.txt
    Absolute path: C:\Users\MyName\filename.txt
    Writeable: true
    Readable: true
    File size in bytes: 0

    Note: There are many available classes in the Java API that can be used to read and write files in Java: FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream , etc. Which one to use depends on the Java version you’re working with and whether you need to read bytes or characters, and the size of the file/lines etc.

    Tip: To delete a file, read our Java Delete Files chapter.

    Источник

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