Download presentation
Presentation is loading. Please wait.
1
Introduction to programming in java
Lecture 25 Input from file
2
Input Stream from a File
We can also construct a scanner object that connects to a disk file: File file = new File("myData.txt"); // create a File object Scanner scan = new Scanner( file ); // connect a Scanner to the file
3
Program with Disk Input
The program reads its data from myData.txt, a text file that might have been created with a text editor. The file starts with an integer in character format. The Scanner scans over the beginning spaces until it finds characters that can be converted to int. It stops scanning when it encounters the first space after the digits it is converting.
4
IOException The file myData.txt should exist and should be in the same directory as the program. If the file does not exist, the program cannot construct a Scanner that reads from it. If this happens, the run-time Java system will throw an IOException. Because of this, two things are needed in the program. The main() method must start with the line: public static void main (String[] args) throws IOException And the Java io package must be imported: import java.io.*;
5
hasNextInt() Most files contain a great deal of data. Practical programs must process this data using a loop of some sort. Here is a program that reads a text file that contains many integers and writes the square of each one.
6
Example Run For example, myData.txt contains following data.
7
HasNext Methods
8
User Names the File
9
Example Run
10
Practice Question Write a program that adds all the integers in a file of text integers. Prompt the user for the name of the input file. Write a program which prints the data of whole file.
11
Question 1
12
Question 2
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.