Programming Java Java IO Programming| File Read and Writing | Java...

Java IO Programming| File Read and Writing | Java OOP| CS School

-

Java offers many classes for performing file input and output, or Java IO. There are two categories of file input classes. These includes: Text IO classes, and Binary IO classes. In this article we will talk about Java IO Programming: File input output of text file using Scanner and PrintWriter classes.

Java IO: File Writing

We use the java.io.PrintWriter class to create file and write data to a text file. So for that we first need to create a PrintWriter Object as follows: 

PrintWriter output = new PrintWriter(filename.txt);

Then we can invoke the print, println, and printf methods of  PrintWriter object to write data to a file. An example of file_writing we have mentioned in below code sample:

public class writeData {
   public static void main (String[] args) throws Exception {
     java.io.File myfile = new java.io.File(“file_name.txt“);
       if (myfile.exists()){
         System.out.println(“File already exists”);
         System.exit(0); 
     }
    //creating new file
    java.io.PrintWriter output = new java.io.PrintWriter(myfile);
      output.println(“John T Smith”);
      output.println(“Age: 40”);
    //close the file
      output.close();
  }
}

Here we are invoking the PrintWriter constructor, that will create a new file: file_name.txt, if the specific file does not exists. Here invoking constructor: PrintWriter may throw an IO exception if the same_name file already exists. We previously used System.out.println to write text on console. Here we are using the object output, that will write text on myfile object which is file_name.txt. Here we also need to call the close() method explicitly to close the output file: file_name.txt. Otherwise the file may not be saved properly.

Java IO: File Reading

We know that java.util.Scanner class is necessary to read string and primitive values from the console. A Scanner breaks its input into tokens delimited by whitespace characters. To read from the keyboard, we create a Scanner for System.in, as follows: 

Scanner input = new Scanner(System.in);

However to read from a file Scanner class is also necessary. We can read from file using Scanner class in following manner:

Scanner input = new Scanner (new File (file_name.txt));

Methods in Scanner class that we use frequently are: Scanner(source: File), creates a scanner that produces values scanned from a specified_file. Scanner(source: String), creates scanner that produces values scanned from the specified_string. The Scanner class also has close() method that explicitly close the class. Also the hasNext(): boolean returns true, if scanner has more data to read. Furthermore, the methods – next(): String, nextLine(): String, nextByte(): byte also the parts of Scanner. read more about java Scanner class.

An example of file_reading we have shown in code segment below:

import java.util.Scanner;

Public class readData {
  public static void main (String[] args) throws Exception {
    //creating file instance
     java.io.File myfile = new java.io.File(“file_name.txt“);

    //creating Scanner from file
    Scanner input = new Scanner (myfile);

    //read data from a file
    while (input.hasNext()) {
      String firstName = input.next();
      String mi = input.next();
      int score = input.nextInt();
      System.out.println( firstName + ” ” + ” ” + score);
      }
      input.close();
   }
}

So, here the Scanner(myfile) creates a scanner for myfile: file_name.txt; As we create Scanner object to read values from specific file. Therefore, we have to use java.io.File class to instantiate File object (myfile) to access that specific file. Here’s also in each iteration of while loop, it reads first name, mi, last name, and score from the specific text file. It is not necessary to close the input file, but it is a good practice to do so.

We also can create a Scanner object that will read from specific file, in following way: 

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

Class BasicInputFile {
 
public static void main (string[] args) {

    File myfile = new File(“file_name.txt”);
   
    try {
     Scanner input = new Scanner(myfile);
     String name =input.nextLine();
     int age = input.nextInt();

    System.out.printf(“Name: %s Age: %d”, name, age);
     } catch (FileNotFoundException ex){
      System.out.printf(“ERROR: %s\n”, ex);
     }
}
}

What this Scanner really doing is, it scans through the myfile: “file_name.txt,” and read from the file.

Read more article on java>>

Latest Articles

Property Decorator | Getters Setters and Deleters in Python

In this article, we will talk about the Property Decorator in Python. It enables the class functionality...

Dictionaries | HashMap in Python | Working with Key-Values

Dictionaries in Python is similar to Hashmap comparing to other languages. It stores data as a key-value...

Hash Table | Indexing | Hashing Algorithm | Python Implementation

This article will talk about a high-level view of the Hash Table. As a programmer, this technique...

Eigenvector Eigenvalue | Linear Algebra Fundamentals

Eigenvector ($bar{v}$) in linear algebra is a non-zero vector (matrix) that doesn't change its direction during linear...

Pivot Table | Microsoft Excel | Create Data Insight Easily

Pivot table in microsoft Excel is an useful function that gives us a way to create insight...

Macro Function in Microsoft Excel | Automate Repetitive Task

This article we will talk about the Macro. It is a function in microsoft excel which basically...

Must read

Dictionaries | HashMap in Python | Working with Key-Values

Dictionaries in Python is similar to Hashmap...

You might also likeRELATED
Recommended to you