CS302 File Output  Week 12: Lecture Handout  ©2015 Deppeler

Computer Components: an Overview

Identify which of the main components of a computer are responsible for input and output to running computer programs.

1. Monitor: input | output | both

2. Modem: input | output | both

3. Box: CPU? Motherboard? Device Cards? Hard Disk Drives? Floppy Disk Drives? USB Ports?

4. Mouse: input | output | both

5. Speaker: input | output | both

6. Printer: input | output | both

7. Keyboard: input | output | both

©2015 Deppeler  CS302 File Output Week 12Lecture Handout  Page 1 of ??

CS302 File Output  Week 12: Lecture Handout  ©2015 Deppeler

8. What’s inside the Computer? (1) (2) (3) (4) What other parts can you recognize?

CS302 File Output  Week 12: Lecture Handout  ©2015 Deppeler

Files

Files are pages of data stored on (written to) ”external” devices: floppy drive, hard drive, network filespace, USB drive, cloud server filespace, etc. Use delimiter characters ( / ) to indicate directories along the path to the file.

1. Why is data stored in a file?

2. How do we get information into a file?

3. How do we get information out of a file?

4. Where are files located?

5. What is a relative path?

6. What is an absolute path?

CS302 File Output  Week 12: Lecture Handout  ©2015 Deppeler

File Output and File Input (throws FileNotFoundException)

1. How do you write data from a Java program into a file on the hard drive?

import java.io.*;
public class WriteToFile

{

public static void main(String[] args) throws FileNotFoundException

{

String filename = "answers.txt";
PrintWriter pw = new PrintWriter(filename);
for ( int i=0; i < 100 ; i++ )

{

   pw.print((i+1)+". ");
   int k = (int)(Math.random()*5);
   pw.println( (char)('A' + k) );

}

pw.close();

}
}

2. How do you read data from a file into a Java program?

import java.io.*;
public class ReadFile

{

public static void main(String [] args) throws FileNotFoundException

{

String fn = "output.txt";
File infile = new File(fn);
Scanner in = new Scanner(infile);
int i = 0;
while ( in.hasNextLine() )

{

   String line = in.nextLine();
   System.out.println( i + ". " + line );
   i++;

}

in.close();
System.out.print( "Read "+ i + " lines from file " + fn );

...
}