How to Read Numbers From a Text File in Java
Reading from a file
The Scanner grade 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 gear up upwards a Scanner to read from the output pane, we use the syntax
Scanner input = new Scanner(System.in);
To set upwards a Scanner to read from a text file, we instead apply 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.
Ane small complication you are going to encounter when you try to use 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 have named does not exist, Java may throw a FileNotFound exception. NetBeans will note this possibility and force yous to include some actress code that potentially intercept that exception and handle it should it occur. The code beneath will have care of that:
Scanner input = zip; try { input = new Scanner(new File("numbers.txt")); } grab (Exception ex) { ex.printStackTrace(); }
Should we attempt to open a file that does not exist, the command new File("numbers.txt")
will generate an exception, which will crusade u.s. to enter the catch
block. In the catch block we can tell the exception object to print some additional details about what went incorrect to the output pane.
In add-on to the exception treatment code, you volition also demand to place an import statement at the meridian 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, start by right-clicking on the project in the project pane. (The project is the thing with the coffee cup icon adjacent 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 blazon categories, and so select 'Empty File' from the list of file types on the right. Click Side by side to movement to the second function 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 outset typing data into information technology.
If you need to locate the text file at some afterward point, yous volition 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 elementary example program that demonstrates how to read a listing of integers from a text file:
packet fileexamples; import java.io.File; import java.util.Scanner; public class ReadNumbers { public static void primary(String[] args) { Scanner input = nada; try { input = new Scanner(new File("numbers.txt")); } take hold of (Exception ex) { System.out.println("Tin can not open up file."); System.exit(0); } while(input.hasNextInt()) { int number = input.nextInt(); Arrangement.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 print a message and then exit, otherwise we become on to read data 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 programme volition attempt to read all of the numbers in the text file and print them to the output pane.
1 complexity with input from files is that we may non 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 truthful if there are more numbers available to be read from the file and faux in one case we take read to the end of the file. As you lot tin meet in the example program, we tin use hasNextInt()
to control a while loop that reads numbers from the file until all of the numbers accept been read.
A search trouble
Hither is a typical case of a search trouble: given a list of numbers in a file that announced in no particular lodge, discover the smallest and largest numbers in the file.
To solve this problem we set up ii variables, ane to store the smallest number we have seen and then far, and one to store the largest number nosotros have seen so far. Nosotros offset by reading the starting time number from that file: that number is simultaneously both the smallest and largest number we have seen so far. Then, equally we read through the rest of the numbers in the file we compare each new number against these variables to see whether we have establish a new largest or smallest number.
public static void main(Cord[] args) { Scanner input = zilch; endeavour { input = new Scanner(new File("numbers.txt")); } take hold of (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 autumn in the range from " + smallest + " to " + largest); }
Writing to a file
Sometimes we volition observe ourselves writing programs that generate a lot of output. If nosotros would similar to save that output to use afterwards, we tin can adjust for the program to print its output to a file instead of to the output pane in NetBeans.
The side by side example shows how to do this. For this example I took 1 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 list of all of the prime numbers from i to chiliad.
public static void main(String[] args) { PrintWriter pow = nada; try { pw = new PrintWriter(new File("primes.txt")); } take hold of (Exception ex) { Organization.out.println("Can not open file for writing."); System.get out(0); } int north = 3; while (north < m) { int d = n - 1; while (d > 1) { if (n % d == 0) { break; } d--; } if (d == 1) { prisoner of war.println(n); } n = north + 2; } pw.close(); }
Here are some things to notation virtually this example.
- To print 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 announced in a
effort..catch
construct. - The PrintWriter form has the same 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 you accept to phone call its
close()
method. One of the things a PrintWriter does is to cache its output in retentivity and then periodically affluent that output to the file. Callingclose()
forces the PrintWriter to flush its output to the file.
Source: http://www2.lawrence.edu/fast/GREGGJ/CMSC150/031Files/Files.html
Enregistrer un commentaire for "How to Read Numbers From a Text File in Java"