Read Java File From First to Five Scanner

Reading from a file

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

Scanner input = new Scanner(System.in);        

To prepare a Scanner to read from a text file, we instead utilize the syntax

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

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

Ane small complication you are going to run into when yous attempt to use the code above 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 have named does not exist, Java may throw a FileNotFound exception. NetBeans will annotation this possibility and force you to include some actress code that potentially intercept that exception and handle it should it occur. The lawmaking below will take care of that:

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

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

In improver to the exception handling lawmaking, you will also demand to place an import statement at the meridian of your programme 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 projection pane. (The projection is the thing with the coffee loving cup icon next to it.) From the context card, select the selection New/Other...

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

In this dialog yous will type the proper noun of the file. Clicking Terminate creates and opens the text file for you to offset typing information into it.

If you lot need to locate the text file at some afterward point, you volition be able to access it in the Files pane in NetBeans.

Kickoff example programme - reading numbers from a text file

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

packet fileexamples;  import java.io.File; import java.util.Scanner;  public class ReadNumbers {      public static void main(String[] args) {         Scanner input = zero;         endeavor {             input = new Scanner(new File("numbers.txt"));         } catch (Exception ex) {             Organisation.out.println("Tin can non open file.");             System.get out(0);         }         while(input.hasNextInt()) {             int number = input.nextInt();             System.out.println(number);         }         input.close();     } }        

This program opens a Scanner to read from the text file named "numbers.txt". If the input file is not present, the program will print a bulletin and then leave, otherwise we proceed to read data from the file. One time the Scanner is open on the file, we can use the usual command 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 print them to the output pane.

Ane complication with input from files is that we may non know in advance how many numbers are in the text file. To assistance with this, the Scanner class offers a useful method hasNextInt() that returns truthful if there are more numbers available to be read from the file and imitation once we have read to the cease of the file. As you can encounter in the example program, we tin can use hasNextInt() to control a while loop that reads numbers from the file until all of the numbers take been read.

A search problem

Here is a typical case 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 problem we set up ii variables, one to store the smallest number nosotros have seen so far, and one to store the largest number we have seen and then far. We start by reading the commencement number from that file: that number is simultaneously both the smallest and largest number we have seen so far. And then, as we read through the rest of the numbers in the file we compare each new number against these variables to see whether nosotros take found a new largest or smallest number.

public static void main(String[] args) {     Scanner input = null;     effort {         input = new Scanner(new File("numbers.txt"));     } catch (Exception ex) {         System.out.println("Tin 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();      System.out.println("The numbers in the file fall in the range from " + smallest + " to " + largest); }        

Writing to a file

Sometimes we volition detect ourselves writing programs that generate a lot of output. If nosotros would like to save that output to use subsequently, we tin conform for the program to print its output to a file instead of to the output pane in NetBeans.

The adjacent example shows how to practise this. For this example I took one 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 number numbers from 1 to 1000.

public static void master(String[] args) {     PrintWriter pw = goose egg;     endeavor {         pw = new PrintWriter(new File("primes.txt"));     } catch (Exception ex) {         System.out.println("Can non open file for writing.");         System.exit(0);     }      int n = 3;     while (n < one thousand) {         int d = due north - one;         while (d > 1) {             if (n % d == 0) {                 pause;             }             d--;         }          if (d == 1) {             pw.println(n);         }          n = due north + ii;     }     pw.shut(); }        

Here are some things to note nearly this example.

  • To print to a file nosotros make use 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 try..catch construct.
  • The PrintWriter class has the aforementioned methods every bit System.out. (In fact, System.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. One of the things a PrintWriter does is to enshroud its output in memory and then periodically flush that output to the file. Calling close() forces the PrintWriter to affluent its output to the file.

fourniermorelesucity78.blogspot.com

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

0 Response to "Read Java File From First to Five Scanner"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel