Java's operation 1 of the file 1.

xiaoxiao2021-03-06  78

Recently, when you develop code generators, you need to read the template file, replace the corresponding characters according to the template, then output the desired class, because there is no direct support for the replacement function in Java or C , so when the template character is replaced Need to write a certain code to implement the replacement function. For the operation of the template file, in JDK 1.1, support two new object Reader & Writer, which can only be used to operate text files, while INPUTSTREAM & OUTPUTSTREAM in JDK1.1 can operate on text files or binaries. . The common way to read files with FileReader is: FileReader FileReader = New FileReader ("Test.txt"); BufferedReader BufferReader = New BufferedReader (fr); use br.readline () to read data (Comment: here reading Is a line of rows), then use bufferreader.close () to close the cache, shut down files with FileReader.close (). The common way to write files with FileWrit is: FileWriter FileWriter = New FileWriter ("new_test.txt"); PrintWriter Out = New PrintWriter (FW); write data in file with out.print or out.println, OUT The only difference between .print and Out.println is that the latter writes data or automatically opens a new line. After writing, remember to turn the output with out.close (), close the file with FileWriter.close (). The following example is to read a file content to another file: import java.io. *; Public class test {private static final string template_path = "E:" file.seParetor; // hypothesis file is placed in the E disk Public static void main (string "args) {string linecontent = null; // Used to store readings every line of content TRY {

FileReader fr = new FileReader (TEMPLATE_PATH "test.txt"); BufferedReader br = new BufferedReader (fr); // read the file test.txt FileWriter fw = new FileWriter (TEMPLATE_PATH "new_test.txt"); // Create a new file PrintWriter out = new PrintWriter (fw);

LineContent = new string (); while ((linecontent = br.readline ())! = null) {// Judgment whether all data is read, / * can do a replacement action * / system.out.println (LineContent ); Out.print (linecontent); // Enter data to the new file} out.close (); fw.close ();

} catch (exception e) {E.PrintStackTrace ();

转载请注明原文地址:https://www.9cbs.com/read-93072.html

New Post(0)