Presentation is loading. Please wait.

Presentation is loading. Please wait.

I/O in Java Dennis Burford

Similar presentations


Presentation on theme: "I/O in Java Dennis Burford"— Presentation transcript:

1 I/O in Java Dennis Burford dburford@cs.uct.ac.za

2 Input and Output Obtaining input: –Using BasicIo methods. –Through a GUI Producing output: –Using System.out methods ( System.out.println() ) –Through a GUI Other input/output: files, sockets etc.

3 Streams Java uses the concept of Streams for I/O Data flows from a Writer to a Reader ReaderWriter Stream

4 Why Streams? Stream generalizes input & output –Keyboard electronics different from disk –Input stream makes keyboard and files seem the same to a Reader Input Stream Reader

5 Simplified Keyboard Input… “Java: First Contact” uses BasicIo class –String name = BasicIo.readString(); –int age = BasicIo.readInteger(); Slack textbook uses Keyboard class –String name = Keyboard.readString(); –int age = Keyboard.readInt();

6 Simplified Keyboard Input… Both BasicIo and Keyboard are wrapper classes used to hide detail. In reality, both classes use System.in and other low-level Java classes to operate.

7 System class System class is inside java.lang package Contains 2 variables: public static final InputStream in; public static final PrintStream out; System.in is usually connected to the user’s keyboard. System.out is usually connected to the user’s screen.

8 Using System.in System.in is an InputStream Can use System.in many ways –Directly (low-level access) –Through layers of abstraction (high-level access)

9 Using System.in read() method reads one character at a time. Returns an int Returns –1 for EOF (End of File = Ctrl-Z)

10 Using System.in public static void main(String[] args) throws java.io.IOException { char character; // Prompt for a character and read it System.out.print("Enter a character: "); System.out.flush(); character = (char) System.in.read(); // Display the character typed System.out.println(); System.out.println("You typed " + character); }

11 Using System.in int intChar = System.in.read(); while (intChar != -1) { // Convert to character char character = (char) intChar; System.out.println("Next character is " + character); // Get next one intChar = System.in.read(); }

12 Reading Strings No String-reading methods in System.in To read strings from keyboard, first wrap System.in inside InputStreamReader object: InputStreamReader ISReader = new InputStreamReader(System.in);

13 Reading Strings

14 Next, wrap InputStreamReader object in BufferedReader object: InputStreamReader ISReader = new InputStreamReader(System.in); BufferedReader BufReader = new BufferedReader(ISReader);

15 Reading Strings Can combine these into a single statement: BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in));

16 Reading Strings Can combine these into a single statement: BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in)); InputStream InputStreamReader BufferedReader

17 Reading Strings Methods in BufferedReader –read() –readLine() Read a string by using readLine() method: String str = BufReader.readLine();

18 Reading Strings

19 InputStreamReader, BufferedReader in java.io.* Skeleton for reading: import java.io.*; class ClassName { public static void main(String[] args) throws java.io.IOException { // Create a buffered input stream and attach it to standard // input BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in));... }

20 Example: Reading User’s Name // Reads a user's first name and last name. // Demonstrates use of InputStreamReader, // BufferedReader and the readLine() method. import java.io.*; class ReadInputAsString { public static void main(String[] args) throws java.io.IOException { String firstName, lastName; // Create an input stream and attach it to the standard // input stream BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in));

21 Example: Reading User’s Name // Read a line from the user as a String System.out.print("Enter your first name: "); System.out.flush(); firstName = BufReader.readLine(); // Read a line from the user as a String System.out.print("Enter your last name: "); System.out.flush(); lastName = BufReader.readLine(); // Display the strings System.out.println(); System.out.println("Your name is" + firstName + lastName); }

22 Example: Reading User’s Name // Read a line from the user as a String System.out.print("Enter your first name: "); System.out.flush(); firstName = BufReader.readLine(); // Read a line from the user as a String System.out.print("Enter your last name: "); System.out.flush(); lastName = BufReader.readLine(); // Display the strings System.out.println(); System.out.println("Your name is" + firstName + lastName); } Enter your first name: Linda Enter your last name: Jones Your name is Linda Jones

23 Formatting Numbers Alternative to Integer.parseInt() etc. NumberFormat –Object factory: use getInstance() –parse() takes a string and returns a Number –parse() throws java.text.ParseException General Number class –Return value using intValue(), doubleValue() etc.

24

25 Formatting Numbers from Kbd NumberFormat formatter = NumberFormat.getInstance(); BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter an integer: "); System.out.flush(); String response = BufReader.readLine(); Number numberObj = formatter.parse(response); int numberInt = numberObj.intValue();

26 Formatting Numbers from Kbd NumberFormat formatter = NumberFormat.getInstance(); BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter an integer: "); System.out.flush(); String response = BufReader.readLine(); Number numberObj = formatter.parse(response); int numberInt = numberObj.intValue(); Combine

27 Formatting Numbers from Kbd NumberFormat formatter = NumberFormat.getInstance(); BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter an integer: "); System.out.flush(); int numberInt = formatter.parse( BufReader.readLine() ).intValue();

28 Formatting Numbers from Kbd NumberFormat formatter = NumberFormat.getInstance(); BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter an integer: "); System.out.flush(); int numberInt = formatter.parse( BufReader.readLine() ).intValue(); Don’t forget to throw or catch java.text.ParseException

29 Input Streams: Multiple Values To read several values on one line –Use StringTokenizer object –Breaks one string into component parts –Must still convert numbers (if necessary) StringTokenizer –Constructor takes string –nextToken() method –hasMoreTokens() method

30

31 Input Streams: Multiple Values StringTokenizer tokenizer = new StringTokenizer("42 58"); String token; token = tokenizer.nextToken(); System.out.println(token); // Displays 42 token = tokenizer.nextToken(); System.out.println(token); // Displays 58 BETTER… StringTokenizer tokenizer = new StringTokenizer("42 58"); while (tokenizer.hasMoreTokens()) { System.out.println(tokenizer.nextToken()); }

32 FILES

33 Overview of Files How they are accessed: –sequential: data items must be accessed in the order in which they are stored (ie. start at the beginning and pass through all the items) –direct (or random): items are accessed by specifying their location How information is represented: –text files: data is stored in character form. –binary files: data is stored in internal binary form (faster and more compact than text files).

34 Types of Files Summer.txt Rough winds do shake the darling buds of May\n And Summer’s lease hath all too short a date\n Sometime too hot the eye of heaven shines,\n And oft is his gold complexion dimmed,\n And every fair from fair sometime declines... Numbers.dat Œpôw10Žé¿l%®ú€9câÜ(3xLenfˆx¹ª(Ͻ»¼øß:°µœŒ ÝçMÙ¾à:ˆqfõÑ>|èœ=L¶...

35 Text Files Text file –human-readable with simple tools (Notepad, Ready,...) –Each line terminated by end-of-line marker (‘\n’) –Example:.java files Easy to read and write text files –Advantage of "streams" approach to I/O –Use same classes and methods as System.in and System.out

36 Text Files: The File Class Need File object for each file program uses –File inFile = new File(”Summer.txt"); Purpose –Contains information about the file –A “go-between” for the file –Not the same as the file itself

37 Text Files: The File Class Methods in the File class –exists() : Tells if the file is there –canRead() : Tells if program can read the file –canWrite() : Tells if program can write to the file –delete() : Deletes the file –isDirectory() : Tells if file is really a directory name –isFile() : Tells if the file is a file (not a directory) –length() : Tells the length of the file, in bytes

38 Text Files: The File Class Methods in the File class –exists() : Tells if the file is there –canRead() : Tells if program can read the file –canWrite() : Tells if program can write to the file –delete() : Deletes the file –isDirectory() : Tells if file is really a directory name –isFile() : Tells if the file is a file (not a directory) –length() : Tells the length of the file, in bytes

39 import java.io.*; class TellIfExists { public static void main(String[] args) throws java.io.IOException { File myFile = new File(“Summer.txt”); if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } // end main }

40 import java.io.*; class TellIfExists { public static void main(String[] args) throws java.io.IOException { File myFile = new File(“Summer.txt”); if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } // end main }

41 import java.io.*; class TellIfExists { public static void main(String[] args) throws java.io.IOException { File myFile = new File(“Summer.txt”); if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } // end main }

42 import java.io.*; class TellIfExists { public static void main(String[] args) throws java.io.IOException { File myFile = new File(“Summer.txt”); if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } // end main }

43 import java.io.*; class TellIfExists { public static void main(String[] args) throws java.io.IOException { File myFile = new File(“Summer.txt”); if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } // end main }

44 import java.io.*; class TellIfExists { public static void main(String[] args) throws java.io.IOException { File myFile = new File(“Summer.txt”); if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } // end main }

45 Text Files: Reading from a File Before reading, make sure –File exists and is readable inFile.exists() && inFile.canRead() Attach file to a stream –FileReader object: knows how to read stream from a file –Wrap FileReader object in BufferedReader object BufferedReader works on files just like System.in –read() : read a single character, or -1 if EOF –readLine() : read a line, or null if EOF

46 File FileReader BufferedReader

47 // Initialize the file variable File inFile = new File(”Summer.txt"); // Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile)); // Read from file stream same way as reading // from the keyboard String line = BufReader.readLine(); } else { // Error: Can't read from file }

48 // Initialize the file variable File inFile = new File(”Summer.txt"); // Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile)); // Read from file stream same way as reading // from the keyboard String line = BufReader.readLine(); } else { // Error: Can't read from file }

49 // Initialize the file variable File inFile = new File(”Summer.txt"); // Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile)); // Read from file stream same way as reading // from the keyboard String line = BufReader.readLine(); } else { // Error: Can't read from file }

50 // Initialize the file variable File inFile = new File(”Summer.txt"); // Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile)); // Read from file stream same way as reading // from the keyboard String line = BufReader.readLine(); } else { // Error: Can't read from file }

51 // Initialize the file variable File inFile = new File(”Summer.txt"); // Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile)); // Read from file stream same way as reading // from the keyboard String line = BufReader.readLine(); } else { // Error: Can't read from file }

52 // Initialize the file variable File inFile = new File(”Summer.txt"); // Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile)); // Read from file stream same way as reading // from the keyboard String line = BufReader.readLine(); } else { // Error: Can't read from file } line = “ Rough winds do shake the darling buds of May ”

53 Text Files: Reading from a File Can do same things we did with System.in –Read numbers ( NumberFormat ) –Read multiple “tokens” ( StringTokenizer )

54 Text Files: Writing to a File Before writing, make sure either... –File doesn't exist !outFile.exists() –Or file exists, and is writeable outFile.exists() && outFile.canWrite() Combine conditions !outFile.exists() || outFile.canWrite()

55 Text Files: Writing to a File Attach file to a stream –FileWriter object: knows how to write stream to a file –Wrap FileWriter object in BufferedWriter object –Wrap BufferedWriter object in PrintWriter object

56 File FileWriter BufferedWriter PrintWriter

57 // Initialize the file variable File outFile = new File(”New.txt"); // Make sure that the file either doesn't exist or // we can write to it if (!outFile.exists() || outFile.canWrite()) { // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile))); // Write to the file pWriter.println( “This is the first line!” ); } else { // Error: Can't write to the file }

58 // Initialize the file variable File outFile = new File(”New.txt"); // Make sure that the file either doesn't exist or // we can write to it if (!outFile.exists() || outFile.canWrite()) { // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile))); // Write to the file pWriter.println( “This is the first line!” ); } else { // Error: Can't write to the file }

59 // Initialize the file variable File outFile = new File(”New.txt"); // Make sure that the file either doesn't exist or // we can write to it if (!outFile.exists() || outFile.canWrite()) { // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile))); // Write to the file pWriter.println( “This is the first line!” ); } else { // Error: Can't write to the file }

60 // Initialize the file variable File outFile = new File(”New.txt"); // Make sure that the file either doesn't exist or // we can write to it if (!outFile.exists() || outFile.canWrite()) { // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile))); // Write to the file pWriter.println( “This is the first line!” ); } else { // Error: Can't write to the file }

61 // Initialize the file variable File outFile = new File(”New.txt"); // Make sure that the file either doesn't exist or // we can write to it if (!outFile.exists() || outFile.canWrite()) { // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile))); // Write to the file pWriter.println( “This is the first line!” ); } else { // Error: Can't write to the file }

62 Text Files: Writing to a File System.out and pWriter both output streams –System.out is PrintStream object –pWriter is PrintWriter object –PrintStream and PrintWriter are almost identical ( PrintWriter is newer) –print(), println(), flush() work the same

63 Text Files: Writing to a File System.out and pWriter both output streams –System.out is PrintStream object –pWriter is PrintWriter object –PrintStream and PrintWriter are almost identical ( PrintWriter is newer) –print(), println(), flush() work the same pWriter.print("This goes "); pWriter.println("to the file");

64 Text Files: Writing to a File Once finished writing to the file, close it pWriter.close();

65 Java I/O Summary

66 Reading from Keyboard –BufferedReader( InputStreamReader( System.in )) Writing to Screen –System.out Reading from File –BufferedReader( FileReader( File )) Writing to File –PrintWriter( BufferedWriter( FileWriter( File )))


Download ppt "I/O in Java Dennis Burford"

Similar presentations


Ads by Google