Skip to content Skip to sidebar Skip to footer

Java Read Text File and Print Numbers

Reading from a file

The Scanner class is useful non just for reading input that the user types into the output pane, but can also exist used to read text data from a file. To set a Scanner to read from the output pane, we use the syntax

Scanner input = new Scanner(System.in);        

To set up 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 noun of the text file we want to read from.

I minor complication yous are going to encounter when you endeavor to utilise the code higher up to create a Scanner to read from a file is that the Scanner needs a File object to tell it where the file it should read from is. Unfortunately, creating a File object may generate an exception: if the file we accept named does not exist, Coffee may throw a FileNotFound exception. NetBeans volition note this possibility and force you to include some extra lawmaking that potentially intercept that exception and handle information technology should it occur. The lawmaking beneath will take care of that:

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

Should we attempt to open a file that does non exist, the command new File("numbers.txt") will generate an exception, which volition crusade us to enter the take hold of block. In the catch block we tin tell the exception object to print some additional details about what went wrong to the output pane.

In addition to the exception treatment code, you will besides need to place an import statement at the top of your program to import the File class:

import java.io.File;        

Creating a text file to read from

To brand a text file in NetBeans, beginning by right-clicking on the projection in the project pane. (The projection is the thing with the java cup icon next to it.) From the context card, select the option New/Other...

In the dialog box that appears, select the category Other at the lesser of the list of file type categories, so select 'Empty File' from the list of file types on the correct. Click Next to move to the second office of the New File dialog.

In this dialog yous will blazon the name of the file. Clicking Finish creates and opens the text file for you to commencement typing data into it.

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

First example programme - reading numbers from a text file

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

package fileexamples;  import java.io.File; import java.util.Scanner;  public form ReadNumbers {      public static void main(String[] args) {         Scanner input = naught;         try {             input = new Scanner(new File("numbers.txt"));         } catch (Exception ex) {             System.out.println("Tin can not open file.");             System.exit(0);         }         while(input.hasNextInt()) {             int number = input.nextInt();             Organisation.out.println(number);         }         input.close();     } }        

This programme opens a Scanner to read from the text file named "numbers.txt". If the input file is not present, the program will impress a message and and so get out, otherwise we go along to read data from the file. Once the Scanner is open on the file, nosotros can utilize the usual control nextInt() to read the next available integer from the file. The plan will attempt to read all of the numbers in the text file and impress them to the output pane.

One complication with input from files is that nosotros may not know in accelerate how many numbers are in the text file. To assist with this, the Scanner class offers a useful method hasNextInt() that returns truthful if at that place are more numbers available to be read from the file and simulated one time we have read to the terminate of the file. As yous tin run across in the instance programme, we can utilize hasNextInt() to control a while loop that reads numbers from the file until all of the numbers have been read.

A search trouble

Here is a typical example of a search trouble: given a list of numbers in a file that appear in no detail order, notice the smallest and largest numbers in the file.

To solve this problem nosotros set up two variables, one to store the smallest number we have seen so far, and one to store the largest number nosotros accept seen so far. We outset past reading the first number from that file: that number is simultaneously both the smallest and largest number we have seen so far. And so, as we read through the rest of the numbers in the file we compare each new number against these variables to come across whether we take found a new largest or smallest number.

public static void main(String[] args) {     Scanner input = zero;     effort {         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.shut();      Organization.out.println("The numbers in the file fall in the range from " + smallest + " to " + largest); }        

Writing to a file

Sometimes we will find ourselves writing programs that generate a lot of output. If we would like to relieve that output to apply later, we can adjust for the programme to print its output to a file instead of to the output pane in NetBeans.

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

public static void main(String[] args) {     PrintWriter pow = null;     try {         pw = new PrintWriter(new File("primes.txt"));     } grab (Exception ex) {         System.out.println("Can not open file for writing.");         Organization.exit(0);     }      int north = iii;     while (north < yard) {         int d = n - 1;         while (d > 1) {             if (northward % d == 0) {                 suspension;             }             d--;         }          if (d == 1) {             pw.println(n);         }          n = north + 2;     }     prisoner of war.shut(); }        

Hither are some things to note most this example.

  • To impress to a file nosotros make apply of a PrintWriter object that prints its output to a file.
  • Because we are working with a file, the code that creates the PrintWriter object has to appear in a endeavor..grab construct.
  • The PrintWriter class has the same methods as Organisation.out. (In fact, Arrangement.out is itself a PrintWriter that prints its output to the output pane instead of to a file.)
  • When you are done writing to a PrintWriter you have to call its close() method. Ane of the things a PrintWriter does is to cache its output in retentivity and and then periodically affluent that output to the file. Calling shut() forces the PrintWriter to flush its output to the file.

bratchersubmiliand.blogspot.com

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

Post a Comment for "Java Read Text File and Print Numbers"