Text File Input/Output In Java 12 April 2011
CSC 102 Computer Science Principles Introduction The class File Defines platform-independent methods for manipulating a native file. Does not allow access to file contents. I.e., it allows you to get info about a file, not to read its content. See Java API info for class File in java.io package. Note some of the methods. CSC 102 Computer Science Principles
CSC 102 Computer Science Principles Terminology Stream-An object that allows for the flow of data between your program and some I/O device or some file. Text file-A file containing ASCII data. Binary File-A file handled as sequences of binary digits. CSC 102 Computer Science Principles
Text File Input Using Scanner Basically the same as for keyboard input except replace System.in in the scanner constructor with the stream that is connected to the text file, or with the new File instance of the text file itself. Create a stream of the class Scanner. Connect it to a text file for reading. Use Scanner methods as appropriate. Test for end of a text file with hasNextInt, hasNextLine, etc., to see whether there is more input. CSC 102 Computer Science Principles
Text File Input Using Scanner Create a File object named “anyFile” whose physical file name is “Any.dat”. Create a stream of the class Scanner. Scanner inputStream = null; Connect the stream to a text file by creating a new Scanner object that uses the File object we already created. inputStream= new Scanner(anyFile); CSC 102 Computer Science Principles
Example: Read text file “any.dat” SeeTextFileScannerExample1A.java and TextFileScannerExample1.java CSC 102 Computer Science Principles
Example: Read from a file named at execution time. See TextFileScannerExample2.java CSC 102 Computer Science Principles
CSC 102 Computer Science Principles Text File Output Construct a PrintWriter stream object. PrintWriter pw = new PrintWriter(filename); Now, Use the print() and println() methods to write to the file. Example: pw.println(“This will be a line of text in the file.”); Finally, use close() to disconnect the file from the program. CSC 102 Computer Science Principles
CSC 102 Computer Science Principles Text File Output See TextFileOutDemoSimpler.java CSC 102 Computer Science Principles
CSC 102 Computer Science Principles Text File Output Exercise: Convert TextFileOutDemoSimpler.java to copy one file’s contents to another. CSC 102 Computer Science Principles
CSC 102 Computer Science Principles File I/O There are several variations on file I/O besides what is shown here . . . CSC 102 Computer Science Principles