How to Read Int From Text File Using Scanner in Java

Reading from a file

The Scanner class is useful not merely for reading input that the user types into the output pane, merely can likewise exist used to read text data from a file. To set a Scanner to read from the output pane, we apply the syntax

Scanner input = new Scanner(System.in);        

To ready a Scanner to read from a text file, we instead use the syntax

Scanner input = new Scanner(new File("numbers.txt"));        

where numbers.txt is the proper name of the text file we want to read from.

One pocket-sized complexity you are going to encounter when you try to utilise the code to a higher place to create a Scanner to read from a file is that the Scanner needs a File object to tell information technology where the file it should read from is. Unfortunately, creating a File object may generate an exception: if the file we take named does not exist, Java may throw a FileNotFound exception. NetBeans will note this possibility and strength you to include some actress code that potentially intercept that exception and handle it should it occur. The code below volition accept intendance of that:

Scanner input = null; try {     input = new Scanner(new File("numbers.txt")); } catch (Exception ex) {     ex.printStackTrace(); }        

Should nosotros try to open a file that does not exist, the command new File("numbers.txt") will generate an exception, which will cause u.s.a. to enter the catch block. In the catch block we can tell the exception object to print some boosted details virtually what went wrong to the output pane.

In addition to the exception handling code, you will too need to place an import statement at the elevation of your program to import the File class:

import java.io.File;        

Creating a text file to read from

To make a text file in NetBeans, start by right-clicking on the project in the project pane. (The project is the thing with the coffee cup icon next to it.) From the context menu, select the option New/Other...

In the dialog box that appears, select the category Other at the bottom of the list of file type categories, and then select 'Empty File' from the listing of file types on the right. Click Next to motility to the second part of the New File dialog.

In this dialog you will type the proper name of the file. Clicking Finish creates and opens the text file for yous to start typing information into information technology.

If you lot need to locate the text file at some later indicate, you lot will exist able to access it in the Files pane in NetBeans.

Kickoff example programme - reading numbers from a text file

Here is the code for a first simple example program that demonstrates how to read a list of integers from a text file:

parcel fileexamples;  import coffee.io.File; import java.util.Scanner;  public grade ReadNumbers {      public static void main(String[] args) {         Scanner input = nothing;         try {             input = new Scanner(new File("numbers.txt"));         } catch (Exception ex) {             Organisation.out.println("Can non open file.");             Arrangement.exit(0);         }         while(input.hasNextInt()) {             int number = input.nextInt();             Organisation.out.println(number);         }         input.close();     } }        

This program opens a Scanner to read from the text file named "numbers.txt". If the input file is non present, the programme will print a message and then exit, otherwise nosotros go on to read data from the file. Once the Scanner is open on the file, nosotros tin use the usual command nextInt() to read the next bachelor integer from the file. The program will effort to read all of the numbers in the text file and print them to the output pane.

One complexity with input from files is that nosotros may not know in advance how many numbers are in the text file. To help with this, the Scanner class offers a useful method hasNextInt() that returns true if there are more numbers available to be read from the file and false once we have read to the end of the file. As you can see in the case program, nosotros can employ hasNextInt() to command a while loop that reads numbers from the file until all of the numbers have been read.

A search problem

Hither is a typical example of a search problem: given a list of numbers in a file that announced in no particular order, find the smallest and largest numbers in the file.

To solve this trouble we gear up 2 variables, one to store the smallest number we have seen then far, and 1 to shop the largest number we have seen so far. Nosotros first by reading the first number from that file: that number is simultaneously both the smallest and largest number nosotros have seen so far. Then, as we read through the residual of the numbers in the file we compare each new number against these variables to encounter whether we have found a new largest or smallest number.

public static void main(String[] args) {     Scanner input = aught;     try {         input = new Scanner(new File("numbers.txt"));     } catch (Exception ex) {         System.out.println("Can not open file.");         Organization.exit(0);     }      int smallest = input.nextInt();     int largest = smallest;      while(input.hasNextInt()) {         int number = input.nextInt();         if(number < smallest)             smallest = number;         if(number > largest)             largest = number;     }     input.close();      Organisation.out.println("The numbers in the file fall in the range from " + smallest + " to " + largest); }        

Writing to a file

Sometimes nosotros will find ourselves writing programs that generate a lot of output. If nosotros would like to relieve that output to utilise later on, we can arrange for the program to print its output to a file instead of to the output pane in NetBeans.

The next instance shows how to do this. For this example I took i of the examples from the lecture on loops and rewrote it to write its output to a file instead of to System.out. The example is a program that generates a listing of all of the prime numbers from one to 1000.

public static void main(String[] args) {     PrintWriter pw = aught;     try {         pw = new PrintWriter(new File("primes.txt"));     } catch (Exception ex) {         Arrangement.out.println("Tin can non open file for writing.");         System.exit(0);     }      int northward = 3;     while (n < thou) {         int d = north - i;         while (d > 1) {             if (due north % d == 0) {                 suspension;             }             d--;         }          if (d == 1) {             pw.println(n);         }          n = n + 2;     }     pw.close(); }        

Here are some things to note about this instance.

  • To print to a file we make use of a PrintWriter object that prints its output to a file.
  • Considering we are working with a file, the code that creates the PrintWriter object has to announced in a attempt..grab construct.
  • The PrintWriter class has the same methods as System.out. (In fact, Arrangement.out is itself a PrintWriter that prints its output to the output pane instead of to a file.)
  • When yous are done writing to a PrintWriter you accept to call its close() method. I of the things a PrintWriter does is to enshroud its output in memory and so periodically flush that output to the file. Calling close() forces the PrintWriter to flush its output to the file.

cooperkinesen.blogspot.com

Source: http://www2.lawrence.edu/fast/GREGGJ/CMSC150/031Files/Files.html

0 Response to "How to Read Int From Text File Using Scanner in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel