The information acquisition, management operation and file traversal under the directory are introduced before. Then how to read and write the data inside the file? This is the content of this paper. File tool is powerful, but it can not read and write files directly, but it can only carry out reading and writing operations with the help of other tools. For write operations, you need to use FileWriter with File tools. The process of creating a writer object is simple. Just pass the file object when calling FileWriter's construction method, and then you can call the following method of the writer to write data to the file.
write: write a string to a file. Note that there are multiple overloading methods with the same name.
Appnd: Writes strings to files, too. Literally, the append method is like appending a string to the end of a file, but that's not the case. The append method is written in the same location as the write method. The difference between them is that the append method writes a null pointer to a file as a null, while the write method does not support writing a null pointer.
close: close the file writer.
String together a series of write operations to form the following process of write file code. Note that several methods of file writer need to capture input and output anomalies IOException:
private static String mFileName = "D:/test/aac.txt"; // Write file code with hidden trouble. Documents will not be closed when an exception occurs private static void writeFileSimple() { String str = "The sun beyond the mountains glows; the Yellow Riverseawards flows.\n"; File file = new File(mFileName); // Create a file object with a specified path try { FileWriter writer = new FileWriter(file); // Create a file writer writer.write(str); // Write a string to a file writer.close(); // Close file } catch (IOException e) { e.printStackTrace(); } }
The above example code seems to be well-structured, but there are many hidden dangers. Because the close method is called only in the normal branch, the exception branch does not call the method, so once an exception occurs, the opened file will not be closed properly, resulting in file damage. The solution is to add a final statement after try/catch and a call to close method in the final statement block, so the improved code for writing files is as follows:
// The improved code for writing files. Close files in final block private static void writeFileWithFinally() { String str = "The sun beyond the mountains glows; the Yellow Riverseawards flows.\n"; File file = new File(mFileName); // Create a file object with a specified path FileWriter writer = null; try { writer = new FileWriter(file); // Create a file writer writer.write(str); // Write a string to a file } catch (IOException e) { e.printStackTrace(); } finally { // Release file resources regardless of exceptions if (writer != null) { try { writer.close(); // Close file } catch (IOException e) { e.printStackTrace(); } } } }
The improved code does eliminate the risk of abnormal closure of files, but the whole code is procrastinating with a few more lines at once. To this end, start with Java 7, the try-with-resources expression is supported by the try statement, which means to take some resources to try to work and release them automatically after the attempt. Concrete method is to add parentheses after try and fill in the creation statement of resource objects in parentheses. As long as the resource class implements the AutoCloseable interface, the program will automatically call the close method of the resource after try/catch. Thus, there is no need to supplement the final code block, nor to explicitly call the close method. The optimization code for automatic resource management is as follows:
// Write file code to automatically release resources private static void writeFileWithTry() { String str = "The sun beyond the mountains glows; the Yellow Riverseawards flows.\n"; File file = new File(mFileName); // Create a file object with a specified path // The new features of Java 7, resources declared in try(...), are automatically released after try/catch. // It is equivalent to the compiler automatically supplementing the resource release operation in the final code block. // The resource class must implement the java.lang.AutoCloseable interface so that the close method is called by the system. // Generally speaking, file I/O, socket, database connection and so on have all realized the interface. try (FileWriter writer = new FileWriter(file)) { writer.write(str); // Write a string to a file } catch (IOException e) { e.printStackTrace(); } }
Thus, the use of "try-with-resources" mode of code immediately reduced to a few lines, can be said to be a good news for programmers.
Corresponding to the write operation is the read operation, which uses the file reader FileReader, which still works with the File tool partner. Creating a reader object also passes the file object when calling the construction method of FileReader. The invocation methods provided by the reader are listed as follows:
Skip: skip several characters. Note that FileReader's skip method skips the number of characters, not bytes.
read: read data from files to byte arrays. Note that there are multiple overloading methods with the same name.
close: close the file reader.
Examples of regular code that reads data from a file through a file reader are as follows:
// Read file code with hidden trouble. Documents will not be closed when an exception occurs private static void readFileSimple() { File file = new File(mFileName); // Create a file object with a specified path try { FileReader reader = new FileReader(file); // Create a file reader //reader.skip(2); //character stream skip method skips the number of characters, not bytes char[] temp = new char[(int) file.length()]; reader.read(temp); // Read data from files to byte arrays String content = new String(temp); // Converting character arrays to strings System.out.println("content="+content); reader.close(); // Close file } catch (IOException e) { e.printStackTrace(); } }
The above read file code still does not take into account the resource release problem when an exception occurs, so it needs to be improved by adding a final statement. Close method is called in the final code block to close the file. The improved code is as follows:
// Improved Read File Code private static void readFileWithFinally() { File file = new File(mFileName); // Create a file object with a specified path FileReader reader = null; try { reader = new FileReader(file); // Create a file reader char[] temp = new char[(int) file.length()]; reader.read(temp); // Read data from files to byte arrays String content = new String(temp); // Converting character arrays to strings System.out.println("content="+content); } catch (IOException e) { e.printStackTrace(); } finally { // Release file resources regardless of exceptions if (reader != null) { try { reader.close(); // Close file } catch (IOException e) { e.printStackTrace(); } } } }
Like FileWriter, FileReader implements the AutoCloseable interface, which means that it also applies to try-with-resources rules. Then put the creation statement of the file reader in parentheses after try, and the previous final statement block can be deleted entirely, because the program will release the reader resources automatically after try/catch. At this point, the read file code that automatically releases resources becomes the following:
// Read file code to automatically release resources private static void readFileWithTry() { File file = new File(mFileName); // Create a file object with a specified path // The new features of Java 7, resources declared in try(...), are automatically released after try/catch. // It is equivalent to the compiler automatically supplementing the resource release operation in the final code block. // The resource class must implement the java.lang.AutoCloseable interface so that the close method is called by the system. // Generally speaking, file I/O, socket, database connection and so on have all realized the interface. try (FileReader reader = new FileReader(file)) { char[] temp = new char[(int) file.length()]; reader.read(temp); // Read data from files to byte arrays String content = new String(temp); // Converting character arrays to strings System.out.println("content="+content); } catch (IOException e) { e.printStackTrace(); } }
Despite the fact that there are several lines in the code above, there are not many lines without comments. The time-saving and labor-saving convenient writing method should be promoted vigorously. Without special circumstances, the above try-with-resources writing method will be used in future related codes.
See more Java technology articles< Java Development Notes (Preface) Chapter Program Directory>