100 likes | 267 Views
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer. Introductory Points. Java I/O is primarily “stream-oriented.” Data flows into the program and out of the program, like a ‘stream.’ We have ‘input’ streams and ‘output’ streams. “Standard” I/O streams:
E N D
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer
Introductory Points • Java I/O is primarily “stream-oriented.” • Data flows into the program and out of the program, like a ‘stream.’ • We have ‘input’ streams and ‘output’ streams. • “Standard” I/O streams: • System.in – defaults to the keyboard • System.out – defaults to the monitor • System.err – defaults to where System.out is: monitor. • These are all public and static and found in the System class of the Java API.
Standard I/O • We’ve used standard I/O in creating Scanner objects to process data normally associated with standard input (keyboard) and standard output (monitor). • “I/O exceptions” are handled for us by Scanner. • Many ‘opportunity for problems in doing any kind of input / output: Examples include files not defined; file not found; formats not what were expected, EOF early, etc. and other exceptions. • I/O in Java can be very complicated. • We oftentimes need to be able to read text data or purebinary data. These can come from external files, memory, or from strings. • Here, we will emphasize input/output as pertains to external files.
The java I/O package • The java.io package provides us classes that let us define desired input and output streams. • Because we use the classes themselves (as in class.method) the methods we use are public and static. • Recall: static methods don’t need to be part of an object to use them, as in the Math class – recall: Math.sqrt() • (Math is the class; sqrt() is method and we simply say, Math.sqrt()…) • We did not have to instantiate an object of type Math in order to access the method! (note capitalized class name followed by member name) • Recall: in die1.roll(), die1 was an object; hence object.method() call…. • Some classes provide for buffering (manipulate data in stream itself.) • Like, we can change format and more (ahead) • What we do is to combine a number of these classes to lock in to exactly what we want to do our input/output. • The general topic of java I/O is huge and we will cover only what we need here.
The java.io package • To restate: so many I/O operations can cause problems and `throw’ an “I/O Exception” when we are trying to do I/O operations such as read() or write() operations. • We must either • Use a try…catch combination: • ‘catch’ the exception in a ‘try’ block and process it • (use a try() … catch() sequence) or • Recognize that any method that may catch a problem must have a ‘throws’ clause in the header of the method where the I/O is attempted. • For now, we will elect this approach. • At this time, it is simpler…
Very Simplified I/O – for now • We will just use: throws IOException clause for File I/O. • For much more, see Chapter 10 slides.
Code – for Input import java.io.*; // You need this to access the classes cited below. public static void main (String[ ] args) throws IOException. //you need the “throws.” Why?? You must also // 1. download (right click, Save Target As) your input file (from my web page), and // 2. put it (drag it) into your project folder so the program can find it and read lines from it. FileInputStream fis1 = new FileInputStream(“Countries.txt"); // much more in Chapter 10 BufferedReader br1 = new BufferedReader(new InputStreamReader(fis1)); // for an input file to be read// // or // FileReader fr = new FileReader(“Countries.txt”); // BufferedReader br = new BufferedReader (fr); String inputString; String countryName String countryWhatever…. // additional attributes here… inputString = br1.readLine(); //reads one complete line (record) from the input file into inputString. // Now you need to get to the parts of the inputString. We call this ‘parsing’ the input. Consider: while (inputString != null) // looks at entire string you just read into inputString { countryName = inputString.substring(0, 15).trim() //read country name countryWhatever = inputString.substring(15, 30), //read country capital countryPopulatiion = Integer.parseInt(inputString.substring(55, 60)); //read country code # // Note: these are not the precise character positions in ‘your’ file. // You will need to check appropriate attribute field lengths. // Look in your book about substring method. Echoprint everything to verify!!! // <other code – like creating an object from these attributes.> inputString = br1.readLine(); // read next input line. } //end while loop br1.close(); //Close input file being read
With a few more comments: FileReader fr = new FileReader(“Countries.Small.txt”); BufferedReader br = new BufferedReader (fr); // Sample names made up to show how the parsing works: String inputString; String someName, someCapital; // but declare one attribute per line. Int somePop; // Note: this has nothing to do with creating objects or the array. // Only ensures you are able to access the individual attributes from each input line. // Once you verify all this, you can comment out the print lines. inputString = br1.readLine(); //reads one complete line (record) from the input file into inputString. // Now you need to get to the parts of the inputString. We call this ‘parsing’ the input. Consider: while (inputString != null) // looks at entire string you just read into inputString { someName = inputString.substring(0, 15).trim() //read country name // echo print to verify you ‘read in and parse what you think you did. System.out.println (“ some Name read in was: “ + someName); someCapital = inputString.substring(15, 30), //read country capital System.out.println (“some Capital read in was: “ + someCapital); somePop = Integer.parseInt(inputString.substring(55, 62)); //read country code # // Statements like these are used to extract specific positions from the input record. // Note: these are not the precise character positions in ‘your’ file. // Look in your book about substring method. Echo print everything to verify!!! …. Other code (later: create object and move into array….Later!) // <other code – like creating an object from these attributes.> inputString = br1.readLine(); // read next input line. } //end while loop
Code – for Output • Must include up top: import java.io.*; // this lets us use the classes below. • Alter your method header as follows: //much more in Chapter 10…. public static void main (String[ ] args) throws IOException. // you need this! • Sample code: (from book) String file = “test.dat”; // name your output file FileWriter fw = new FileWriter (file); // creates object fw of type FileWriter. BufferedWriter bw = new BufferedWriter (fw); // creates object bw of type ... PrintWriter outFile = new PrintWriter (bw); // creates object outFile of type .. • …. <other code> • outFile.print (value + “ “); // writes this as a stream. Try it! • outFile.println (); // prints a blank line in the file • … <other code> • outFile.close(); // at end, close the file • This writes to an output file.
More Later • In using a standard IDE such as NetBeans, your input file needs to be in your project package so your program can find it. • Be certain to move it (drag it) into your package and test accessing the file from your package before you zip up your project and send it to me.