Upload
others
View
15
Download
0
Embed Size (px)
Citation preview
CS 200 - Programming I: File Input / Output
Marc Renault
Department of Computer SciencesUniversity of Wisconsin – Madison
Fall 2019TopHat Sec 3 (1:20 PM) Join Code: 682357TopHat Sec 4 (3:30 PM) Join Code: 296444
Output Formatting Streams Paths File I/O
Output Formatting
Output Formatting Streams Paths File I/O
Output / String Formatting
String.format(String format, Object... args)System.out.format(String format, Object... args)System.out.printf(String format, Object... args)
String formatThe format string.A template string with placeholders (format specifiers) forthe arguments.
Object... argsVarargs – Variadic or variable arity method.Allows any number of objects.
1/22
Output Formatting Streams Paths File I/O
Output / String Formatting
String.format(String format, Object... args)System.out.format(String format, Object... args)System.out.printf(String format, Object... args)
String formatThe format string.A template string with placeholders (format specifiers) forthe arguments.
Object... argsVarargs – Variadic or variable arity method.Allows any number of objects.
1/22
Output Formatting Streams Paths File I/O
Output / String Formatting
String.format(String format, Object... args)System.out.format(String format, Object... args)System.out.printf(String format, Object... args)
String formatThe format string.A template string with placeholders (format specifiers) forthe arguments.
Object... argsVarargs – Variadic or variable arity method.Allows any number of objects.
1/22
Output Formatting Streams Paths File I/O
Format SpecifiersFormat Conversion Specification
%[arg_idx$][flags][width][.precision]type
2/22
Output Formatting Streams Paths File I/O
Format SpecifiersFormat Conversion Specification
%[arg_idx$][flags][width][.precision]type
arg_idx$The position of the argument in the argument list (1-based).
flags- Left-align the output.+ Prepend a “+” for positive numeric types.
(space) prepend a space for positive numeric types.0 Prepend with zeros (requires the width option).( Negative numbers enclosed in parentheses., Locale-specific grouping separators.
2/22
Output Formatting Streams Paths File I/O
Format SpecifiersFormat Conversion Specification
%[arg_idx$][flags][width][.precision]type
arg_idx$The position of the argument in the argument list (1-based).
flags- Left-align the output.+ Prepend a “+” for positive numeric types.
(space) prepend a space for positive numeric types.0 Prepend with zeros (requires the width option).( Negative numbers enclosed in parentheses., Locale-specific grouping separators.
2/22
Output Formatting Streams Paths File I/O
Format SpecifiersFormat Conversion Specification
%[arg_idx$][flags][width][.precision]type
widthMinimum number of characters.
.precisionFor floats: number of digits to the right of the decimal.For strings: maximum number of characters to output.Rest: Not applicable, causes exception.
2/22
Output Formatting Streams Paths File I/O
Format SpecifiersFormat Conversion Specification
%[arg_idx$][flags][width][.precision]type
widthMinimum number of characters.
.precisionFor floats: number of digits to the right of the decimal.For strings: maximum number of characters to output.Rest: Not applicable, causes exception.
2/22
Output Formatting Streams Paths File I/O
Format SpecifiersFormat Conversion Specification
%[arg_idx$][flags][width][.precision]type
typeb,B A boolean.s,S A string.c,C A char.d integer as a decimal integer.o integer as a octal integer.
x,X integer as a hexadecimal integer.
Note: Upper-case conversion converts argument to upper-case.
2/22
Output Formatting Streams Paths File I/O
Format SpecifiersFormat Conversion Specification
%[arg_idx$][flags][width][.precision]type
typef float in decimal notation: [-]ddd.ddd.
e,E float in scientific notation: [-]d.ddde±dd.a,A float in hexadecimal notation.g,G float in f or e (resp. E), depending on magnitude.% Prints a literal “%”.n Platform specific line separator.
Note: Upper-case conversion converts argument to upper-case.
2/22
Output Formatting Streams Paths File I/O
TopHat Question 1
What is the output?
System.out.printf("%B %d 0x%08x",true , 1, 15);
3/22
Output Formatting Streams Paths File I/O
TopHat Question 2
What is the output?
System.out.printf("%4$c %3$C %2c %1$C",’a’, ’b’, ’c’, ’d’);
4/22
Output Formatting Streams Paths File I/O
TopHat Question 3
What is the output?
System.out.printf("%4$C %c %3$C %c %2$C %c %1$C %c",’a’, ’b’, ’c’, ’d’);
5/22
Output Formatting Streams Paths File I/O
Streams
Output Formatting Streams Paths File I/O
Standard Output StreamSystem.out.print("Hello\nWorld!");
Buffer:
Console:
Console:HelloConsole:HelloWorld!
System.outReference to PrintStream object.Default behaviour is to output to console.Buffered output:
Print methods adds data to buffer.Buffered data is output periodically.
6/22
Output Formatting Streams Paths File I/O
Standard Output StreamSystem.out.print("Hello\nWorld!");
H e l l o \n W o r l d !
Buffer:
Console:
Console:HelloConsole:HelloWorld!
System.outReference to PrintStream object.Default behaviour is to output to console.Buffered output:
Print methods adds data to buffer.Buffered data is output periodically.
6/22
Output Formatting Streams Paths File I/O
Standard Output StreamSystem.out.print("Hello\nWorld!");
W o r l d !
Buffer:
Console:
Console:Hello
Console:HelloWorld!
System.outReference to PrintStream object.Default behaviour is to output to console.Buffered output:
Print methods adds data to buffer.Buffered data is output periodically.
6/22
Output Formatting Streams Paths File I/O
Standard Output StreamSystem.out.print("Hello\nWorld!");
Buffer:
Console:Console:Hello
Console:HelloWorld!
System.outReference to PrintStream object.Default behaviour is to output to console.Buffered output:
Print methods adds data to buffer.Buffered data is output periodically.
6/22
Output Formatting Streams Paths File I/O
Standard Input StreamScanner sc = new Scanner(System.in);String s = sc.next ();
Buffer:
Console:
Console:Hello World!
System.inReference to InputStream object.Default behaviour is to input from the console.Buffered input:
Input enters a buffer.Buffered data is read periodically.
7/22
Output Formatting Streams Paths File I/O
Standard Input StreamScanner sc = new Scanner(System.in);String s = sc.next ();
H e l l o W o r l d !
Buffer:
Console:
Console:Hello World!
System.inReference to InputStream object.Default behaviour is to input from the console.Buffered input:
Input enters a buffer.Buffered data is read periodically.
7/22
Output Formatting Streams Paths File I/O
Standard Input StreamScanner sc = new Scanner(System.in);String s = sc.next ();
W o r l d !
Buffer:
Console:
Console:Hello World!
System.inReference to InputStream object.Default behaviour is to input from the console.Buffered input:
Input enters a buffer.Buffered data is read periodically.
7/22
Output Formatting Streams Paths File I/O
Paths
Output Formatting Streams Paths File I/O
Navigating the File System/
homerenault
workspace
Current Working Directory (CWD)Current location in the file system.Denoted by: .The directory from which the jvmwas launched.
Relative PathA path relative to the CWD.To move up: ..
Absolute PathA path that starts at the root of thefile system.Root: ’/’
8/22
Output Formatting Streams Paths File I/O
Navigating the File System/home/renault/workspace
Current Working Directory (CWD)Current location in the file system.Denoted by: .The directory from which the jvmwas launched.
Relative PathA path relative to the CWD.To move up: ..
Absolute PathA path that starts at the root of thefile system.Root: ’/’
8/22
Output Formatting Streams Paths File I/O
Navigating the File System/home/renault/workspace
CS200ExbinData
InOut
srcPalindrome
binsrc
OrdinalExbinsrc
CmdLinebinsrc
Current Working Directory (CWD)Current location in the file system.Denoted by: .The directory from which the jvmwas launched.
Relative PathA path relative to the CWD.To move up: ..
Absolute PathA path that starts at the root of thefile system.Root: ’/’
8/22
Output Formatting Streams Paths File I/O
Navigating the File System/home/renault/workspace
CS200ExbinData
InOut
srcPalindrome
binsrc
OrdinalExbinsrc
CmdLinebinsrc
Current Working Directory (CWD)Current location in the file system.Denoted by: .The directory from which the jvmwas launched.
Relative PathA path relative to the CWD.To move up: ..
Absolute PathA path that starts at the root of thefile system.Root: ’/’
8/22
Output Formatting Streams Paths File I/O
Navigating the File System/home/renault/workspace
CS200ExbinData
InOut
srcPalindrome
binsrc
OrdinalExbinsrc
CmdLinebinsrc
Current Working Directory (CWD)Current location in the file system.Denoted by: .The directory from which the jvmwas launched.
Relative PathA path relative to the CWD.To move up: ..
Absolute PathA path that starts at the root of thefile system.Root: ’/’
8/22
Output Formatting Streams Paths File I/O
Navigating the File System/home/renault/workspace
CS200ExbinData
InOut
srcPalindrome
binsrc
OrdinalExbinsrc
CmdLinebinsrc
Current Working Directory (CWD)Current location in the file system.Denoted by: .The directory from which the jvmwas launched.
Relative PathA path relative to the CWD.To move up: ..
Absolute PathA path that starts at the root of thefile system.Root: ’/’ 8/22
Output Formatting Streams Paths File I/O
Navigating the File System/home/renault/workspace
CS200ExbinData
InOut
srcPalindrome
binsrc
OrdinalExbinsrc
CmdLinebinsrc
TopHat Question 4Is “./Palindrome/src” an absolute or arelative path?
TopHat Question 5Is “/home/renault/workspace/CmdLine”an absolute or a relative path?
TopHat Question 6If the CWD is/home/renault/workspace/CS200Ex/bin,what is the (shortest) relative path to In?
8/22
Output Formatting Streams Paths File I/O
Navigating the File System/home/renault/workspace
CS200ExbinData
InOut
srcPalindrome
binsrc
OrdinalExbinsrc
CmdLinebinsrc
TopHat Question 4Is “./Palindrome/src” an absolute or arelative path?
TopHat Question 5Is “/home/renault/workspace/CmdLine”an absolute or a relative path?
TopHat Question 6If the CWD is/home/renault/workspace/CS200Ex/bin,what is the (shortest) relative path to In?
8/22
Output Formatting Streams Paths File I/O
Navigating the File System/home/renault/workspace
CS200ExbinData
InOut
srcPalindrome
binsrc
OrdinalExbinsrc
CmdLinebinsrc
TopHat Question 4Is “./Palindrome/src” an absolute or arelative path?
TopHat Question 5Is “/home/renault/workspace/CmdLine”an absolute or a relative path?
TopHat Question 6If the CWD is/home/renault/workspace/CS200Ex/bin,what is the (shortest) relative path to In?
8/22
Output Formatting Streams Paths File I/O
File I/O
Output Formatting Streams Paths File I/O
File Classjava.io.File
ConstructorFile f = new File(pathToFile)
Creates a File object, but not an actual file on the disc.pathToFile – Path to file.All the instance methods are base on this path.
Permissionsboolean canRead() – Can read the contents?boolean canWrite() – Can change the contents?boolean canExecute() – Can execute the path?There are also methods to set the permissions.
9/22
Output Formatting Streams Paths File I/O
File Classjava.io.File
ConstructorFile f = new File(pathToFile)
Creates a File object, but not an actual file on the disc.pathToFile – Path to file.All the instance methods are base on this path.
File Testsboolean exists() – Does the file exist?boolean isFile() – Is it a normal file?boolean isDirectory() – Is it a directory?boolean isHidden() – Is it a directory?
9/22
Output Formatting Streams Paths File I/O
File Classjava.io.File
ConstructorFile f = new File(pathToFile)
Creates a File object, but not an actual file on the disc.pathToFile – Path to file.All the instance methods are base on this path.
Other File Propertieslong lastModified() – Date last modified.long length() – Number of bytes.String getPath() – Returns the path.String getAbsolutePath() – Returns the absolute path.String getParent() – Returns the parent from the path.
9/22
Output Formatting Streams Paths File I/O
File Classjava.io.File
ConstructorFile f = new File(pathToFile)
Creates a File object, but not an actual file on the disc.pathToFile – Path to file.All the instance methods are base on this path.
Basic Operationsboolean createNewFile() – Create an empty file.boolean renameTo(File dest) – Move to dest.boolean delete() – Delete the path.void deleteOnExit() – Delete the path when the JVMterminates.
9/22
Output Formatting Streams Paths File I/O
File Class
java.io.File
ConstructorFile f = new File(pathToFile)
Creates a File object, but not an actual file on the disc.pathToFile – Path to file.All the instance methods are base on this path.
Directory Operationsboolean mkdir() – Create director based on path.boolean mkdirs() – Create all the directories in the path.String[] list() – List files contained in directory.
9/22
Output Formatting Streams Paths File I/O
Eclipse CWDTopHat Question 7
What is the CWD in this case?This code is in an Eclipse project called CS200Example:import java.io.File;
public class FileInfo {
public static void main(String [] arg){File f = new File(".");System.out.println(f.getPath ());System.out.println(f.getAbsolutePath ());
}}
When run, the output is:./home/renault/workspace/CS200Examples/.
10/22
Output Formatting Streams Paths File I/O
Creating FilesTopHat Question 8
What is the output, assuming proper permissions andthat the files don’t yet exist?import java.io.File;import java.io.IOException;
public class CreateFile{public static void main(String [] arg){
File f = new File("tmp.txt");File f2 = new File("/home/renault/tmp2.txt");File f3 = new File("/home/renault/tmp2.txt");try{
if(!f.createNewFile ()){System.out.print("f exists.");
}if(!f2.createNewFile ()){
System.out.print("f2 exists.");}if(!f3.createNewFile ()){
System.out.print("f3 exists.");}
}catch(IOException e){
System.out.print("Exception!");}
}}
11/22
Output Formatting Streams Paths File I/O
Deleting FilesTopHat Question 9
What is the output, assuming proper permissions andthat the files don’t yet exist?import java.io.File;
public class DeleteFile {
public static void main(String [] args){File f = new File("tmp.txt");File f2 = new File("t.txt");try{
f.createNewFile ();if(f.delete ()){
System.out.println("f deleted.");}if(f2.delete ()){
System.out.println("f2 deleted.");}
}catch(Exception e){
System.out.println("Exception!");}
}}
12/22
Output Formatting Streams Paths File I/O
Listing FilesTopHat Question 10
How would you run the following code from thecommand line so that it prints out the contents of thecurrent directory?
import java.io.File;
public class FileListing {
public static void main(String [] args) {File f = new File(args [0]);for (String s: f.list ()) {
System.out.println(s);}
}
}
13/22
Output Formatting Streams Paths File I/O
File InputIn Java, there are many ways to read a file. You can...
Start with...java.io.File
java.io.FileReader
java.io.FileInputStream
Wrap it in...java.util.Scanner
java.io.Readerwrapped in a java.io.BufferedReader
Exercise: Write a simple cat.Write a program that prints out every line from the filenamepassed in on the command line.
14/22
Output Formatting Streams Paths File I/O
File InputIn Java, there are many ways to read a file. You can...
Start with...java.io.File
java.io.FileReader
java.io.FileInputStream
Wrap it in...java.util.Scanner
java.io.Readerwrapped in a java.io.BufferedReader
Exercise: Write a simple cat.Write a program that prints out every line from the filenamepassed in on the command line.
14/22
Output Formatting Streams Paths File I/O
File InputIn Java, there are many ways to read a file. You can...
Start with...java.io.File
java.io.FileReader
java.io.FileInputStream
Wrap it in...java.util.Scanner
java.io.Readerwrapped in a java.io.BufferedReader
Exercise: Write a simple cat.Write a program that prints out every line from the filenamepassed in on the command line.
14/22
Output Formatting Streams Paths File I/O
File InputIn Java, there are many ways to read a file. You can...
Start with...java.io.File
java.io.FileReader
java.io.FileInputStream
Wrap it in...java.util.Scanner
java.io.Readerwrapped in a java.io.BufferedReader
Exercise: Write a simple cat.Write a program that prints out every line from the filenamepassed in on the command line.
14/22
Output Formatting Streams Paths File I/O
Simple cat (one file) with Scanner
import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;
public class CatScannerFile {
public static void main(String [] args) {if(args.length >= 1) {
Scanner s = null;try {
File f = new File(args [0]);s = new Scanner(f);while(s.hasNextLine ()) {
System.out.println(s.nextLine ());}
}catch(FileNotFoundException e) {
System.out.println("File not found: " + args [0]);}finally {
if(s != null)s.close ();
}}
}}
15/22
Output Formatting Streams Paths File I/O
Simple cat (one file) with BufferedReader
import java.io.FileReader;import java.io.FileNotFoundException;import java.io.BufferedReader;import java.io.IOException;
public class CatBuffReadFile {
public static void main(String [] args) throws IOException {if(args.length >= 1) {
BufferedReader br = null;FileReader fr = null;try {
fr = new FileReader(args [0]);br = new BufferedReader(fr);while(br.ready ()) {
System.out.print(br.readLine ());}
}catch(FileNotFoundException e) {
System.out.println("File not found: " + args [0]);}finally {
if(br != null)br.close ();
}}
}}
16/22
Output Formatting Streams Paths File I/O
Basic try with Resources
try ( SomeCloseable1 a = new SomeCloseable1 (...);SomeCloseable2 b = new SomeCloseable2 (...) ) {
tryStmtBlock;}
try-with-resourcesNew in Java 7.try statement in which you declare the resources.The declared resources are closed automatically in theopposite order of their creation.The resources must implement AutoCloseable.
17/22
Output Formatting Streams Paths File I/O
try-with-resources-catch-finallyTopHat Question 11
If an exception is thrown in the try statement block whathappens in what order?
try ( SomeCloseable1 a = new SomeCloseable1 (...);SomeCloseable2 b = new SomeCloseable2 (...) ) {
tryStmtBlock;}catch (Exception e) {
catchStmtBlock;}finally {
finallyStmtBlock;}
18/22
Output Formatting Streams Paths File I/O
Simple cat (one file) with Scanner andtry-with-resources
import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;
public class CatScannerFileTryRes {
public static void main(String [] args) {if(args.length >= 1) {
try (Scanner s = new Scanner(new File(args [0]))) {while(s.hasNextLine ()) {
System.out.println(s.nextLine ());}
}catch(FileNotFoundException e) {
System.out.println("File not found: " + args [0]);}
}}
}
19/22
Output Formatting Streams Paths File I/O
File OutputIn Java, there are many ways to write to a file. You can...
Start with...java.io.File
java.io.FileWriter
java.io.FileOutputStream
Wrap it in...java.io.PrintWriter
java.io.Writerwrapped in a java.io.BufferedWriter
Some ExampleszyBooks has examples of FileOutputStreamwrapped in aPrintWriter.
Let’s consider File wrapped in a PrintWriter.
20/22
Output Formatting Streams Paths File I/O
File OutputIn Java, there are many ways to write to a file. You can...
Start with...java.io.File
java.io.FileWriter
java.io.FileOutputStream
Wrap it in...java.io.PrintWriter
java.io.Writerwrapped in a java.io.BufferedWriter
Some ExampleszyBooks has examples of FileOutputStreamwrapped in aPrintWriter.
Let’s consider File wrapped in a PrintWriter.
20/22
Output Formatting Streams Paths File I/O
File OutputIn Java, there are many ways to write to a file. You can...
Start with...java.io.File
java.io.FileWriter
java.io.FileOutputStream
Wrap it in...java.io.PrintWriter
java.io.Writerwrapped in a java.io.BufferedWriter
Some ExampleszyBooks has examples of FileOutputStreamwrapped in aPrintWriter.
Let’s consider File wrapped in a PrintWriter.
20/22
Output Formatting Streams Paths File I/O
File OutputIn Java, there are many ways to write to a file. You can...
Start with...java.io.File
java.io.FileWriter
java.io.FileOutputStream
Wrap it in...java.io.PrintWriter
java.io.Writerwrapped in a java.io.BufferedWriter
Some ExampleszyBooks has examples of FileOutputStreamwrapped in aPrintWriter.
Let’s consider File wrapped in a PrintWriter.
20/22
Output Formatting Streams Paths File I/O
File OutputIn Java, there are many ways to write to a file. You can...
Start with...java.io.File
java.io.FileWriter
java.io.FileOutputStream
Wrap it in...java.io.PrintWriter
java.io.Writerwrapped in a java.io.BufferedWriter
Some ExampleszyBooks has examples of FileOutputStreamwrapped in aPrintWriter.Let’s consider File wrapped in a PrintWriter.
20/22
Output Formatting Streams Paths File I/O
Output ExampleTopHat Question 12
How many lines are written to test.txt when the code isexecuted with java FileOutput 10 test.txt 10000?import java.util.Random;import java.io.File;import java.io.PrintWriter;import java.io.FileNotFoundException;
public class FileOutput {public static void main(String [] args) {
if(args.length >= 3) {int numVals = Integer.parseInt(args [0]);int modCols = numVals % 4;numVals = numVals + (modCols != 0 ? 4 - modCols : 0);try (PrintWriter pout = new PrintWriter(new File(args [1]))) {
Random rand = new Random ();for(int i = 0; i < numVals; i += 4)
pout.printf("%8d\t%8d\t%8d\t%8d\n",rand.nextInt(Integer.parseInt(args [2])),rand.nextInt(Integer.parseInt(args [2])),rand.nextInt(Integer.parseInt(args [2])),rand.nextInt(Integer.parseInt(args [2])));
}catch(FileNotFoundException e) {
System.out.println("Unable to open output file: " + args [1]);}
}}
}21/22
Output Formatting Streams Paths File I/O
Further Reading
COMP SCI 200: Programming IzyBooks.com, 2015.zyBook code:WISCCOMPSCI200Fall2019
Chapter 11. File Input / Output
22/22
Appendix References
Appendix
Appendix References
References
Appendix References
Image Sources I
https://brand.wisc.edu/web/logos/
http://www.zybooks.com/
23/22