COP 3503 FALL 2012 Shayan Javed Lecture 12 - PowerPoint PPT Presentation

Cop 3503 fall 2012 shayan javed lecture 12
Download
1 / 66

  • 79 Views
  • Uploaded on
  • Presentation posted in: General

COP 3503 FALL 2012 Shayan Javed Lecture 12. Programming Fundamentals using Java. Input/Output (IO). I/O. So far we have looked at modeling classes. I/O. So far we have looked at modeling classes Not much in the way of Input. Input. 3 ways of providing input to the program:. Input.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha

Download Presentationdownload

COP 3503 FALL 2012 Shayan Javed Lecture 12

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Cop 3503 fall 2012 shayan javed lecture 12

COP 3503 FALL 2012ShayanJavedLecture 12

Programming Fundamentals using Java


Cop 3503 fall 2012 shayan javed lecture 12

Input/Output (IO)


Cop 3503 fall 2012 shayan javed lecture 12

I/O

  • So far we have looked at modeling classes


Cop 3503 fall 2012 shayan javed lecture 12

I/O

  • So far we have looked at modeling classes

  • Not much in the way of Input...


Input

Input

  • 3 ways of providing input to the program:


Input1

Input

  • 3 ways of providing input to the program:

    • Pass parameters directly to the program


Input2

Input

  • 3 ways of providing input to the program:

    • Pass parameters directly to the program

    • Command-line input from the user


Input3

Input

  • 3 ways of providing input to the program:

    • Pass parameters directly to the program

    • Command-line input from the user

    • Reading in files


Passing parameters

Passing parameters

  • When running the program can directly pass parameters to it


Passing parameters1

Passing parameters

  • When running the program can directly pass parameters to it

    java ProgramNameparameter1 parameter2 ...


Passing parameters2

Passing parameters

public static void main(String[] args) {

// args is the array of all parameters

// args[0] would be the first parameter

}


Passing parameters3

Passing parameters

public static void main(String[] args) {

// args is the array of all parameters

// args[0] would be the first parameter

}

Let’s look at an example


Command line input

Command-line input

  • Receive input from the console during execution


Command line input1

Command-line input

  • Receive input from the console during execution

  • Use the Scanner class


The scanner class

The Scanner class

  • Used for reading data


The scanner class1

The Scanner class

  • Used for reading data

  • Constructors:

    • Scanner(InputStream)

      • InputStream = System.in


The scanner class2

The Scanner class

  • Used for reading data

  • Constructors:

    • Scanner(InputStream)

      • InputStream = System.in

    • Scanner(String)


The scanner class3

The Scanner class

  • Used for reading data

  • Constructors:

    • Scanner(InputStream)

      • InputStream = System.in

    • Scanner(String)

    • Scanner(File)


The scanner class4

The Scanner class

  • Methods:

    • booleanhasNext() : If scanner has more tokens


The scanner class5

The Scanner class

  • Methods:

    • booleanhasNext() : If scanner has more tokens

    • String next() :Returns the next String

    • intnextInt() :Returns the next int

    • doublenextDouble() : Returns the next double


The scanner class6

The Scanner class

  • Methods:

    • booleanhasNext() : If scanner has more tokens

    • String next() :Returns the next String

    • intnextInt() :Returns the next int

    • doublenextDouble() : Returns the next double

    • voiduseDelimiter(pattern: String) :Set’s the delimiting pattern

      (“ “ by default)


The scanner class7

The Scanner class

  • Methods:

    • booleanhasNext() : If scanner has more tokens

    • String next() :Returns the next String

    • intnextInt() :Returns the next int

    • doublenextDouble() : Returns the next double

    • voiduseDelimiter(pattern: String) :Set’s the delimiting pattern

      (“ “ by default)

    • void close():Closes the Scanner


Command line input2

Command-line input

  • Use the “next..” methods to read from the standard input


Command line input3

Command-line input

  • Use the “next..” methods to read from the standard input

    importjava.util.Scanner;

    Scannerscanner = newScanner(System.in);

    System.out.print(“Enter number1: “);

    double number1 = scanner.nextDouble();

    System.out.print(“Enter number2: “);

    double number2 = scanner.nextDouble();

    System.out.println(“The addition of the two numbers: “ + (number1 + number2));


File input

File Input

  • Ability to read files essential to any language.


File input1

File Input

  • Ability to read files essential to any language.

  • Two ways to store data:

    • Text format:


File input2

File Input

  • Ability to read files essential to any language.

  • Two ways to store data:

    • Text format:

      • Human-readable form

      • Can be read by text editors


File input3

File Input

  • Ability to read files essential to any language.

  • Two ways to store data:

    • Text format:

      • Human-readable form

      • Can be read by text editors

    • Binary format:

      • Used for executable programs

      • Cannot be read by text editors


The file class

The File class

  • java.io package

  • Represents a “file” object

  • Used for input/output through data streams, the file system and serialization.


The file class1

The File class

  • Constructors:

    • File(pathname: String):Creates a File object for the specified

      pathname. pathname = directory or file


The file class2

The File class

  • Constructors:

    • File(pathname: String):Creates a File object for the specified

      pathname. pathname = directory or file

    • File(parent: String, child: String):Creates a File object for the child

      under the directory parent. child may be a filename or subdirectory.


The file class3

The File class

  • Methods:

    • boolean exists() : If the file exists


The file class4

The File class

  • Methods:

    • boolean exists() : If the file exists

    • booleancanRead() :If the file exists and we can read it

    • booleancanWrite() :If the file exists and we can write to it


The file class5

The File class

  • Methods:

    • boolean exists() : If the file exists

    • booleancanRead() :If the file exists and we can read it

    • booleancanWrite() :If the file exists and we can write to it

    • void isDirectory() :if the object is a directory

    • void isFile() :if the object is a file


The file class6

The File class

  • Methods:

    • boolean exists() : If the file exists

    • booleancanRead() :If the file exists and we can read it

    • booleancanWrite() :If the file exists and we can write to it

    • void isDirectory() :if the object is a directory

    • void isFile() :if the object is a file

    • String getName() :Returns the name of the file


The file class7

The File class

  • Methods:

    • boolean exists() : If the file exists

    • booleancanRead() :If the file exists and we can read it

    • booleancanWrite() :If the file exists and we can write to it

    • void isDirectory() :if the object is a directory

    • void isFile() :if the object is a file

    • String getName() :Returns the name of the file

    • boolean delete() :Deletes the file and returns true

      if succeeded

    • renameTo(dest: File) :Tries to rename the file and returns true

      if succeeded


Reading files

Reading Files

  • Use the Scanner class

  • new Scanner(File)


Reading files1

Reading Files

  • How does Scanner really work?


Reading files2

Reading Files

  • How does Scanner really work?

  • Breaks file contents into tokens

    • Uses a delimiter


Reading files3

Reading Files

  • How does Scanner really work?

  • Breaks file contents into tokens

    • Uses a delimiter

    • Delimiter by default is whitespace


Reading files4

Reading Files

  • How does Scanner really work?

  • Breaks file contents into tokens

    • Uses a delimiter

    • Delimiter by default is whitespace

  • Reads a token, converts it to the required type


Reading files5

Reading Files

  • How does Scanner really work?

  • Breaks file contents into tokens

    • Uses a delimiter

    • Delimiter by default is whitespace

  • Reads a token, converts it to the required type

  • Can change the delimiter – useDelimiter() method


Reading files6

Reading Files

// Reads in the file and outputs all the tokens

Scanner input = newScanner(newFile(“test.txt”));

while (input.hasNext()) {

System.out.println(input.next());

}


Reading files7

Reading Files

// Reads in the file and outputs all the tokens

Scanner input = newScanner(newFile(“test.txt”));

while (input.hasNext()) {

System.out.println(input.next());

}

ERROR – WON’T COMPILE


Reading files8

Reading Files

// Reads in the file and outputs all the tokens

Scanner input = newScanner(newFile(“test.txt”));

while (input.hasNext()) {

System.out.println(input.next());

}

ERROR – WON’T COMPILE

The constructor throws a FileNotFoundException


Reading files9

Reading Files

// Reads in the file and outputs all the tokens

try {

Scanner input = newScanner(newFile(“test.txt”));

while (input.hasNext()) {

System.out.println(input.next());

}

} catch (FileNotFoundExceptionfe) {

fe.printStackTrace();

}


Reading files10

Reading files

  • Have to be careful. Suppose a file contains the line:

    • 34 567


Reading files11

Reading files

  • Have to be careful. Suppose a file contains the line:

    • 34 567

      What will be the contents of intValue and line

      after the following code is executed?

      Scanner in = newScanner(newFile(“test.txt”));

      intintValue = in.nextInt();

      String line = in.nextLine();


Reading files12

Reading files

Scannerscanner = newScanner(“file.txt”);

Treats the String “file.txt” as the source, NOT the file “file.txt”


Writing files

Writing Files

  • Use the PrintWriter class


Writing files1

Writing Files

  • Use the PrintWriter class

  • Constructors:

    • PrintWriter(File file):Creates a PrintWriter for the specified File

    • PrintWriter(String name):Creates a PrintWriter for the specified File with the name


The printwriter class

The PrintWriter class

  • Methods:

    • void print(String) : Writes a String


The printwriter class1

The PrintWriter class

  • Methods:

    • void print(String) : Writes a String

    • void print(int) : Writes an int

    • void print(float) : Writes a float


The printwriter class2

The PrintWriter class

  • Methods:

    • void print(String) : Writes a String

    • void print(int) : Writes an int

    • void print(float) : Writes a float

    • void println(String) :Writes a String but also adds a line separator


The printwriter class3

The PrintWriter class

  • Methods:

    • void print(String) : Writes a String

    • void print(int) : Writes an int

    • void print(float) : Writes a float

    • void println(String) :Writes a String but also adds a line separator

    • void flush() :Flushes the output stream. Ensures writing to the file


The printwriter class4

The PrintWriter class

  • Methods:

    • void print(String) : Writes a String

    • void print(int) : Writes an int

    • void print(float) : Writes a float

    • void println(String) :Writes a String but also adds a line separator

    • void flush() :Flushes the output stream. Ensures writing to the file

    • void close() :Closes the output stream.


Writing files2

Writing Files

PrintWriter output = null;

try {

output = newPrintWriter(newFile(“test”));

// creates a file if it does not exist;

// discards the current content if the file exists

output.print("John T Smith "); output.println(90);

output.print("Eric K Jones "); output.println(85);

output.flush();

}

catch(IOExceptionioe) {

System.out.println(ioe.toString());

}

finally { if (output != null) output.close(); }


Writing files3

Writing Files

  • Problem: What if you want to append to the file not replace it?


Writing files4

Writing Files

  • Problem: What if you want to append to the file not replace it?

  • Solution 1: Read the whole file, then write it back.


Writing files5

Writing Files

  • Problem: What if you want to append to the file not replace it?

  • Solution 1: Read the whole file, then write it back.

    • Cumbersome and too much work


Writing files6

Writing Files

  • Problem: What if you want to append to the file not replace it?

  • Solution 1: Read the whole file, then write it back.

    • Cumbersome and too much work

  • Solution 2: Use the FileWriter class


Writing files7

Writing Files

  • Problem: What if you want to append to the file not replace it?

  • Solution 1: Read the whole file, then write it back.

    • Cumbersome and too much work

  • Solution 2: Use the FileWriter class

    • FileWriter(Filefile, boolean append)


Writing files8

Writing Files

  • Problem: What if you want to append to the file not replace it?

  • Solution 1: Read the whole file, then write it back.

    • Cumbersome and too much work

  • Solution 2: Use the FileWriter class

    • FileWriter(Filefile, boolean append)

    • PrintWriter pw = newPrintWriter(new FileWriter(file, true) )


Writing files9

Writing Files

PrintWriter output = null;

try {

output = newPrintWriter(newFile(“test”));

// creates a file if it does not exist;

// discards the current content if the file exists

output.print("John T Smith "); output.println(90);

output.print("Eric K Jones "); output.println(85);

output.flush();

}

catch(IOExceptionioe) {

System.out.println(ioe.toString());

}

finally { if (output != null) output.close(); }


Writing files append

Writing Files – Append

PrintWriter output = null;

try {

output = newPrintWriter( newFileWriter(newFile(“test”), true) );

// creates a file if it does not exist;

// discards the current content if the file exists

output.print("John T Smith "); output.println(90);

output.print("Eric K Jones "); output.println(85);

output.flush();

}

catch(IOExceptionioe) {

System.out.println(ioe.toString());

}

finally { if (output != null) output.close(); }


Summary

Summary

  • Use Scanner for reading from command-line and files.

    • Based on delimiters

  • Use PrintWriter for writing to files


ad
  • Login