Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Some Filesystem Terminology CS 157 - Introduction to Object-Oriented Programming (OOP) Reading and Writing Files The Java I/O classes The computer’s filesystem is organized into directories; all files stored on disk are organized into directories, which are hierarchically structured. When you first login and open the Terminal program, the default directory is called your home directory Recall that you issue the cd command to change to another directory. The ~ character is a short cut for "home directory". Executing cd ~ always returns to the home directory. Dr. Stephen P. Carl By contrast, a folder is a graphical interface for viewing the contents of your directories. However, you’ll find that some people use "folder" and "directory" interchangably. More Filesystem Terminology Using Programs to Read Files Typically, the procedure is as follows: For every file on the disk, there is a sequence of directories starting from the root directory to the directory which holds the file. This sequence is called the path. Some examples: /home/scarl/Teaching/CS157/Lecture/BadColor.java /home/scarl/Teaching/CS157/Lecture/Cat.java /html/scarl/index.html From anywhere in the filesystem you can find out the current path by typing pwd. First you have to open the file you want to read. To open a file, you first have to know its filename and location. To open an existing file in the current directory you just need its name; the current directory is its location. In BlueJ, the current directory is the one which holds the project files. When running a program on the command line, the current directory is the one where the program is run. To open an existing file not in the current directory, you must specify the entire path. The ~ character can be used as a shortcut for files in your home directory or its subdirectories. 1-4 Reading Files The FileReader class To use the Java I/O (input/output) classes, you must import the package: import java.io.*; To open a file, create an object of type FileReader Pass a String object containing the name of the file to be opened to the FileReader constructor. The FileReader constructor attempts to open the file. An exception is thrown if the file cannot be found or otherwise opened. While FileReader includes methods to read from an open file, they are slow and tedious to use. They read one or more characters at a time from disk, which is slow. A better way is to use buffered reading. Buffering is faster because it allows us to use the fastest disk operations to read an entire disk sector into a buffer. A large portion of the file is read into a buffer provided by the Java I/O object, and then we can read characters quickly, straight from memory. If successful, the resulting object represents the stream of bytes (characters) in the file. The BufferedReader class The BufferedReader class is used to read a stream of bytes from a buffer. Create an object of this type by passing a FileReader object to its constructor. FileReader fr = new FileReader("example.txt")); BufferedReader br = new BufferedReader(fr); Use a BufferedReader object when you want to read data from a file into a String object. If you need the data in other formats (such as integers, real numbers, etc.) there are conversion methods available. Other BufferedReader methods BufferedReader inherits these methods from Reader, its superclass: read for reading a single character read for reading an array of characters (overloaded method) mark to mark a position in the file close to close the file 5-8 A Common Shortcut The following is a common Java idiom: try { br = new BufferedReader(new FileReader(filename)); Writing Data to Files Again, we have to know the file name. Some options to consider: If we need to create a new file for writing, do we throw an exception if the file exists? String s = br.readLine(); } catch (FileNotFoundException ex) { Will we add new content to the end of an existing file, or replace contents of an existing file? System.out.println(ex); } We only need the separate FileReader object if we need to use its specific methods, but this is not common. The default when opening a file for writing is to replace contents of an existing file, if that file exists; otherwise a new file is created from scratch. The BufferedWriter Class Example using Writers try { Like BufferedReader, an object of type BufferedWriter requires a FileWriter object to tell it which file to write to. writer = new BufferedWriter( new FileWriter(filename) ); for (String info: strarray) { The most common method is the write method, which writes one String object (of any length). writer.write(info); writer.newLine(); } Lines are terminated by calling the newLine method. writer.close(); // do NOT forget to close stream when done The close method writes the buffer to disk and closes the file. If this method is not called, the data in the buffer never actually gets written to the file. } catch (IOException e) { // catches file creation errors System.out.println(e); } 9-12 PrintWriter The write method only outputs String objects. What if we want to output other data types? We can fold in yet another class: PrintWriter The PrintWriter class provides the same methods BufferedWriter does and others including the familiar print, println, and printf methods we use with System.out Creating the object: PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("out.txt"))); Output an integer, a space, and a floating point number: out.print(151); out.print(’ ’); out.print(3.14159); Representing Files Finally we have the File class for representing file objects. This class is useful in creating Scanner objects which read files: Scanner input; try { input = new Scanner(new File(filename)); } catch (FileNotFoundException e) { // file not there, explain the problem and exit } 13-16