CSC1401 Input and Output with Files - PowerPoint PPT Presentation

1 / 11
About This Presentation
Title:

CSC1401 Input and Output with Files

Description:

CSC1401. Input and Output (with Files) Learning Goals. Computing concepts ... import java.util.*; // needed for scanner. class IOTesting ... We need to import java.io. ... – PowerPoint PPT presentation

Number of Views:32
Avg rating:3.0/5.0
Slides: 12
Provided by: Wanda6
Category:

less

Transcript and Presenter's Notes

Title: CSC1401 Input and Output with Files


1
CSC1401Input and Output (with Files)
2
Learning Goals
  • Computing concepts
  • Input and output with files in Java
  • Using the Scanner class for file input, and
    PrintWriter for output

3
Recall
  • import java.util. // needed for scanner
  • class IOTesting
  • public static void main(String args)
  • Scanner scan new Scanner(System.in) i
    nt value scan.nextInt()

4
Using Files for input
  • Instead of System.in, we can specify a file
  • Two differences
  • We need to import java.io.
  • Doing file input can lead to an exception if the
    type of data we are requesting doesnt match
    whats in the file

5
Note the changes
  • import java.util. // needed for scanner
  • import java.io. // needed for file
  • class FileIO
  • public static void main(String args) throws
    Exception
  • // throws exception is for file i/o
  • Scanner sc new Scanner(System.in)Scanner
    sc2 new Scanner(new File("data.txt"))int i
    sc2.nextInt()

6
Lets create a file and try
  • Can use Notepad, or just about anything else
    besides MS Word
  • Lets read in a bunch of scores into an array

7
Reading several numbers from a file
  • Scanner sc2 new Scanner(new File("data.txt"))
    int list new int10int count 0
  • while (sc2.hasNextInt() count lt
    10) listcount sc2.nextInt() count
    count 1 for (int i 0 ilt counti)
  • System.out.println("list
  • i " listi)
  • sc2.close() // when you open a file, you//
    should close it

8
File Output
  • Again, well change from System.out to something
    else

9
An example with file output
  • import java.io. // needed for file
  • class IO
  • public static void main(String args)
  • throws Exception// throws exception is for
    file i/o int i 5 PrintWriter steveout
    new PrintWriter(
  • new FileWriter("silly2.txt")) steveout.printl
    n(i " is the value") steveout.close()

10
Summary
  • We use Printwriter for output to a file (the
    Media Computation book has an alternate approach)
  • We use a Scanner object for getting input from a
    file

11
Reading Assignment
  • Media Computation Chapter 12, Section 3 (but not
    section 12.3.3)
Write a Comment
User Comments (0)
About PowerShow.com