Reading Ints From a File in Java

Reading from a file

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

Scanner input = new Scanner(Organisation.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 name of the text file we want to read from.

One pocket-sized complexity you are going to encounter when you try to use the lawmaking in a higher place 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 note this possibility and force you to include some actress code that potentially intercept that exception and handle information technology should it occur. The code beneath will accept care of that:

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

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

In improver to the exception treatment code, yous will as well need to place an import statement at the peak of your programme to import the File class:

import java.io.File;        

Creating a text file to read from

To brand a text file in NetBeans, start by correct-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 lesser 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 office of the New File dialog.

In this dialog you will type the name of the file. Clicking Terminate creates and opens the text file for y'all to beginning typing data into it.

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

First example program - reading numbers from a text file

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

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

This programme opens a Scanner to read from the text file named "numbers.txt". If the input file is non present, the program will print a message and then exit, otherwise we proceed to read information from the file. Once 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.

One complexity with input from files is that we 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 exist read from the file and false once we accept read to the end of the file. Equally you can run across in the example program, we can utilize hasNextInt() to command a while loop that reads numbers from the file until all of the numbers take been read.

A search trouble

Hither is a typical example of a search problem: 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 we gear up two variables, one to store the smallest number nosotros have seen then far, and 1 to store the largest number we take 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. And so, as nosotros read through the rest 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 = null;     endeavor {         input = new Scanner(new File("numbers.txt"));     } catch (Exception ex) {         System.out.println("Can non open up file.");         System.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 nosotros volition find ourselves writing programs that generate a lot of output. If we would like to save that output to utilise later on, nosotros tin can adapt for the program to impress its output to a file instead of to the output pane in NetBeans.

The next case shows how to practise this. For this case 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 plan that generates a list of all of the prime numbers from ane to 1000.

public static void main(String[] args) {     PrintWriter prisoner of war = null;     try {         pw = new PrintWriter(new File("primes.txt"));     } catch (Exception ex) {         System.out.println("Tin non open file for writing.");         Organisation.go out(0);     }      int n = 3;     while (n < 1000) {         int d = n - 1;         while (d > 1) {             if (n % d == 0) {                 intermission;             }             d--;         }          if (d == ane) {             pw.println(north);         }          north = n + 2;     }     prisoner of war.close(); }        

Hither are some things to note nearly this example.

  • To print to a file we make utilise of a PrintWriter object that prints its output to a file.
  • Because nosotros are working with a file, the code that creates the PrintWriter object has to announced in a try..grab construct.
  • The PrintWriter class has the same methods as Organisation.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 cache its output in retention and so periodically flush that output to the file. Calling shut() forces the PrintWriter to flush its output to the file.

thomasfortionle.blogspot.com

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

0 Response to "Reading Ints From a File in Java"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel