Reading a Number From a Txt File as an Integer

Reading from a file

The Scanner class is useful not just 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 a Scanner to read from the output pane, nosotros utilise the syntax

Scanner input = new Scanner(Arrangement.in);        

To gear up 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 nosotros want to read from.

I pocket-size complexity you are going to encounter when you try to utilise the lawmaking to 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 take named does not exist, Java may throw a FileNotFound exception. NetBeans volition notation this possibility and force y'all to include some extra code that potentially intercept that exception and handle information technology should it occur. The lawmaking below will take care of that:

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

Should we endeavor to open up a file that does non exist, the command new File("numbers.txt") volition generate an exception, which volition crusade us to enter the catch cake. In the catch block we can tell the exception object to print some additional details nearly what went wrong to the output pane.

In improver to the exception handling code, you will also need to place an import argument at the top of your program to import the File form:

import java.io.File;        

Creating a text file to read from

To brand a text file in NetBeans, starting time by correct-clicking on the project in the projection pane. (The projection is the thing with the coffee cup icon adjacent to it.) From the context bill of fare, select the option New/Other...

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

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

If you need to locate the text file at some later point, y'all will be able to access it in the Files pane in NetBeans.

First example program - reading numbers from a text file

Hither is the lawmaking for a starting time simple example program that demonstrates how to read a listing of integers from a text file:

package fileexamples;  import java.io.File; import coffee.util.Scanner;  public course ReadNumbers {      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.");             System.exit(0);         }         while(input.hasNextInt()) {             int number = input.nextInt();             System.out.println(number);         }         input.close();     } }        

This plan opens a Scanner to read from the text file named "numbers.txt". If the input file is not present, the program will print a message and so exit, otherwise nosotros go on to read data from the file. Once the Scanner is open on the file, nosotros tin can use the usual command nextInt() to read the next available integer from the file. The program 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 not 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 true if there are more numbers bachelor to be read from the file and simulated once we accept read to the end of the file. As you can encounter in the example program, we can use 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 problem: given a listing of numbers in a file that announced in no particular guild, find the smallest and largest numbers in the file.

To solve this problem nosotros ready ii variables, one to store the smallest number we have seen so far, and one to shop the largest number nosotros have seen so far. We start past reading the first number from that file: that number is simultaneously both the smallest and largest number we have seen and then far. And then, equally nosotros read through the residuum of the numbers in the file we compare each new number against these variables to encounter whether nosotros have found a new largest or smallest number.

public static void main(Cord[] args) {     Scanner input = null;     try {         input = new Scanner(new File("numbers.txt"));     } catch (Exception ex) {         System.out.println("Tin can non open up file.");         System.go out(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 autumn 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 we would like to save that output to use afterward, we tin can suit for the programme to print its output to a file instead of to the output pane in NetBeans.

The next case shows how to practice 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 k.

public static void main(String[] args) {     PrintWriter pw = null;     try {         pw = new PrintWriter(new File("primes.txt"));     } catch (Exception ex) {         Arrangement.out.println("Can not open file for writing.");         Arrangement.leave(0);     }      int due north = 3;     while (northward < 1000) {         int d = north - 1;         while (d > one) {             if (n % d == 0) {                 pause;             }             d--;         }          if (d == i) {             pow.println(northward);         }          n = n + 2;     }     pw.close(); }        

Here are some things to notation about this case.

  • To impress to a file we 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 as 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 y'all accept to call its close() method. One of the things a PrintWriter does is to cache its output in memory so periodically flush that output to the file. Calling close() forces the PrintWriter to affluent its output to the file.

cartyoffirtansay.blogspot.com

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

0 Response to "Reading a Number From a Txt File as an Integer"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel