Notes on Input and Output - Java Programming Language | CSCE 145, Study notes of Computer Science

Material Type: Notes; Class: ALGORITHMIC DESIGN I; Subject: Computer Science & Engineering; University: University of South Carolina - Columbia; Term: Unknown 1989;

Typology: Study notes

Pre 2010

Uploaded on 09/02/2009

koofers-user-oc2
koofers-user-oc2 🇺🇸

3

(2)

9 documents

1 / 35

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Java:
Learning to Program with Robots
Chapter 09: Input and Output
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23

Partial preview of the text

Download Notes on Input and Output - Java Programming Language | CSCE 145 and more Study notes Computer Science in PDF only on Docsity!

Java:Learning to Program with RobotsChapter 09: Input and Output

Chapter Objectives

After studying this chapter, you should be able to: •

Use the

Scanner

class to read information from files and the

PrintWriter

class to write information to files

Locate files using absolute and relative path

Use the

Scanner

class to obtain information from the user

Prompt users for information and check it for errors

Give users more control over programs by using commandinterpreters

Put commonly used classes in a package

Use a dialog box to obtain a filename from the user

Display an image stored in a file

9.1.1: Reading from a File

Most file-processing programs have three important steps:

Locate the file on the disk and construct objects used to access it.

Process the file, one record at a time.

Close the file after the program has finished using it.

public class ReadCountyData{

public static void main(String[ ] args){ Scanner in = new Scanner(

location of input file

while (

the file has another record

{^

read the recordprocess the information in the record } in.close(); } }

9.1.1: Example of Reading from a File (1/2)

import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner; /** Read census data, printing all those lines containing the string "AK" (Alaska).* * @author Byron Weber Becker */ public class ReadCountyData{

public static void main(String[ ] args){^

// Open the file. Scanner in = null;try{ File file = new File(

"2000US_County_data.txt"

in = new Scanner(file); } catch (FileNotFoundException ex){ System.out.println(ex.getMessage());

System.out.println(

"in "

  • System.getProperty(

"user.dir"

System.exit(1); }

9.1.2: Example of Writing to a File (1/2)

import java.io.File;import java.io.FileNotFoundException;import java.io.PrintWriter;import java.util.Scanner; /** Read census data, writing all those lines containing the string "AK" (Alaska) to a file.* * @author Byron Weber Becker */ public class WriteMatchingLines{

public static void main(String[ ] args){^

// Open the files. Scanner in = null;PrintWriter out = null;try{ in = new Scanner(new File(

"2000US_County_data.txt"

out = new PrintWriter(

"Alaska.txt"

} catch (FileNotFoundException ex){ System.out.println(ex.getMessage());

System.out.println(

"in "

  • System.getProperty(

"user.dir"

System.exit(1); }

9.1.2: Example of Writing to a File (2/2)

// Read and process each record. while (in.hasNextLine()){ String record = in.nextLine();

if (record.indexOf(

"AK"

{ out.println(record);} } // Close the files. in.close();out.close(); } }

9.1.3: Data Acquisition Methods

The

Scanner

class contains a number of methods to read a token from

the file and convert it into an appropriate type. For example: File: AK

Anchorage

Corresponding Code:

while (in.hasNextLine()){ String record = in.nextLine();

String stAb = in.next();

// state abbreviation

String cNm = in.next();

// county name

int pop = in.nextInt();

// population

int hh = in.nextInt();

// number of households

int inc = in.nextInt();

// median income

double age = in.nextDouble();

// median age

in.nextLine();if (stAb.equals(

"AK"

{ System.out.println(stAb +

" "

  • cNm +

" "

  • pop +

" "

  • hh +

" "

  • inc +

" "

  • age);

9.1.3: Tracing Data Acquisition Methods

Statement Input

stAb

cNm

inc

age

AK

Anchorage

while (in.hasNextLine())

AK

Anchorage

String stAb = in.next();

AK
AK

Anchorage

String cNm = in.next();

AK

Anchorage

AK

Anchorage

AK

Anchorage

int inc = in.nextInt();

AK

Anchorage

AK

Anchorage

double age = in.nextDouble();

AK

Anchorage

AK

Anchorage

in.nextLine();

AK

Anchorage

AK

Anchorage

AK

Bethel

while (in.hasNextLine())

AK

Anchorage

AK

Bethel

String stAb = in.next();

AK

Anchorage

9.1.3: Data Availability Methods (2/2)

We can also use data availability methods to solve the problem ofmulti-word county names such as “Fairbanks North Star”:

// Read and process each record.^ in.nextLine();

// skip header record

while (in.hasNextLine()){ String stAb = in.next();

// state abbreviation

String cNm = in.next();

// County name – might consist of several tokens

while (!in.hasNextInt()){ cNm +=

" "

  • in.next();

} int pop = in.nextInt();

// population

int hh = in.nextInt();

// number of households

int inc = in.nextInt();

// median income

double age = -1;

// median age – might be NA

if (in.hasNextDouble()){ age = in.nextDouble();} else{ in.next();} in.nextLine(); }

9.2: Representing Objects as Records

Reading a record from a file can get complex!

A single record is an excellent candidate for an object.

Therefore, write a class to represent the information in the records.Initialize the object by writing a constructor that reads from the file.

ReadCounties

+void main(String[ ] args)

County

-String stateAbbrev-String countyName-int population-int numHouseholds-int medianIncome-double medianAge+County(Scanner in)+boolean inState(String stAbbrev)+String toString( )

9.2.1: Reading Records as Objects (2/3)

import java.util.Scanner;public class County extends Object{ private String stateAbbrev;

private String countyName;private int population;private int numHouseholds;private int medianIncome;private double medianAge; /** Read one record from a file to initialize a new instance of County.* @param in The open input file with the file cursor positioned just before the record to read. */ public County(Scanner in){ super();

this.stateAbbrev = in.next();

// state abbreviation

this.countyName = in.next();while (!in.hasNextInt()){ this.countyName +=

" "

  • in.next();

// county name

} this.population = in.nextInt();

// population

this.numHouseholds = in.nextInt();

// number of households

this.medianIncome = in.nextInt();

// median income

this.medianAge = in.nextDouble();

// median age

in.nextLine(); }

9.2.1: Reading Records as Objects (3/3)

/** Is this county in the specified state? / public boolean inState(String stAbbrev){ return this.stateAbbrev.equals(stAbbrev);} /* Represent this county as a string. */ public String toString(){ return this.stateAbbrev +

" "

  • this.countyName +

" "

  • this.population

" "

  • this.numHouseholds +

" "

  • this.medianIncome +

" "

  • this.medianAge;

9.3: Using the File Class

Valid file namesand locations: File f = new File("D:/cs101/A09/counties.txt");File f = new File("D:/cs101/A09old_data/2006_counties.txt");File f = new File("counties.txt");File f = new File("old_data/2005_counties.txt");File f = new File("../A10/explorer.ini");System.out.println(System.getProperty("user.dir"));

D:

Co mm...

cs

cs

A

A

o ld _data

Main.javaServerRecord .javaRepo rt.java

2004_counties.txt2005_counties.txt2006_counties.txt

Main.javaE xplorer.java

counties.txt

exp lo rer.ini

9.3.3: Manipulating Files

A

File

object represents a path to a file or directory that may or may

not exist. Methods provided include:^ boolean canRead()

Can this program read the file?

boolean canWrite()

Can this program write to the file?

boolean delete()

Delete the file or directory. Directories mustbe empty. Returns

true

if it succeeds.

boolean exists()

Returns

true

if the file exists.

StringgetAbsolutePath()

Gets the absolute path for this file.

File getParentFile()

Get a

File

object associated with this file’s

parent directory.

boolean isFile()

Does the path specifies a file?

boolean isDirectory()

Does the path specifies a directory?

long length()

Gets the number of characters in the file.

void mkDir()

Makes the directory represented by this File

. Returns

true

if successful.