Introduction to Java Files
Text Files A sequential collection of data stored on a permanent storage device Hard drive USB memory CD/DVD Has a name and location on computer’s file system … John 9 87 book course … Current position
File Operations Open – Locate the file on computer’s file system – Position the read/write head at the beginning of the file Current position = beginning of the file … John 9 87 book course … Current position
File Operations Open for input (reading) Open for output (writing) – If the file already exists, erase the file content … John 9 87 book course … Current position
File Operations Read – At the current position – Read next string Returns book – Read next integer Error (next piece of data is not integer) … John 9 87 book course … Current position
File Operations -- rules Open for input – The file must exist on the computer’s file system Error otherwise Open for output – If the file already exists, its content is erased Read – The type of the data item at current position should match the type of read instruction (i.e. nextInt, nextDouble, …) Error otherwise – Trying to read past the last piece of data (beyond end of file)will result in an error Write – Must close the file at the end so that it will be written back to the operating system’s file system
File Operations -- Java Open for input – The file must exist on the computer’s file system Error otherwise String fileName= "myFile.txt"; File inpFile = new File(fileName); Scanner in = new Scanner(inpFile); Error if "myFile.txt“ does not exist in the project folder
File Operations -- rules Open for output – If the file already exists, its content is erased String fileName= "myFile.txt"; PrintWriter outFile = new PrintWriter(fileName); – "myFile.txt“ will be erased, if it already exists.
File Operations -- rules Read – The type of the data item at current position should match the type of read instruction (i.e. nextInt, nextDouble, …) Error otherwise – inpFile.next(); » returns the next piece of data in the file as a string – inpFile.nextInt(); – returns the next piece of data in the file as an Integer. The next piece of data in the file must be an integer. – inpFile.nextDouble » returns the next piece of data in the file as a Double. The next piece of data in the file must be a Double.
File Operations -- rules Read – Must ensure that we do not attempt to read beyond the last piece of data in the file – inpFile.hasNext();
File Operations -- rules Write – Must close the file at the end so that it will be written back to the operating system’s file system Similar to a scanner – outFile.print(); – outFile.println(); – outFile.printf(); » See section of the text book » See _resources/Java_printf_method_quick_reference.pdf
File Operations -- rules Close – outFile.close();
File Operations -- rules Method that use file operations must have throws IOException in their headers