File Input in Java - PowerPoint PPT Presentation

1 / 7
About This Presentation
Title:

File Input in Java

Description:

File Input in Java. using files as input. 15-100. 2. Reading from a File ... What about non-formatted files? 15-100. 3. Opening an input File. try ... – PowerPoint PPT presentation

Number of Views:46
Avg rating:3.0/5.0
Slides: 8
Provided by: qata
Category:
Tags: file | input | java

less

Transcript and Presenter's Notes

Title: File Input in Java


1
File Input in Java
  • using files as input

2
Reading from a File
  • A text file is used an input to the application
  • Open the file
  • Read and process one line at the time
  • Close the file when done
  • In general, the input file is formatted
  • Every line has the same number of tokens
  • Tokens are in the same order
  • What about non-formatted files?

3
Opening an input File
  • try
  • FileReader textFile new FileReader(data.txt)
  • BufferedReader inFile new BufferedReader(textFi
    le)
  • System.out.println(File data.txt has been
    opened.)
  • catch (FileNotFoundException fnfe)
  • System.out.println(File data.txt was not
    found!)

4
Reading Line by Line
  • Use the method readLine() as we did when we read
    from the Console window
  • String oneLine inFile.readLine()
  • Then we process the contents of oneline
  • We use the StringTokenizer Class
  • The readLine() method returns
  • either a String object
  • or the value null

5
Reading all the Lines in the File
  • We need to use a loop
  • String oneLine inFile.readline()
  • int number
  • while (oneLine ! null)
  • number Integer.parseInt(oneLine)
  • System.out.println(Number read is
    number)
  • oneLine inFile.readLine()

6
Closing a File
  • In Java, the file must be closed after we read
    the very last line.
  • inFile.close()

7
Homework
  • Read the following
  • Chapter 19, pp. 344-347, 350-353, 359-362
  • Download and read the Word document Files.doc
  • Lab 6 is due Sunday the 16th
Write a Comment
User Comments (0)
About PowerShow.com