Application scenarios: For example, there is a deep-seated file directory structure, such as: Javaapi
Every file has the same content, and we want to change it to something else. Thousands of files are too unwise to modify.
Import Java.io.bufferedreader;import java.io.file;import java.io.fileinputstream;import java.io.InputStreamReader; Import Java.io.printwriter;public class Test {/** * @author itmyhome */public static void Main (string[] Ar GS) {File F = new File ("F:/javaapi/java/lang/reflect"); Print (f, 0); }/** * Traverse folder * * @param f * @param len */public static void print (File f, int len) {Fi le[] File = F.listfiles (); for (int i = 0; i < file.length; i++) {if (File[i].isdirectory ()) {//Determines if folder print (File[i], Len + 1); }//To prevent the output file from overwriting the source file, change the output disk path can also set the other path by itself file Outpath = new file (File[i].getparent (). Replace ("F:", "E: ")); File ReadFile = new file (File[i].getabsolutepath ()); if (!readfile.isdirectory ()) {string filename = Readfile.getname ();//Read to the file name String absolu Tepath = Readfile.getabsolutepath (); Absolute path to File ReadFile (absolutepath, filename, I, outpath); Call ReadFile}}}/** * Read file under folder * * @return */public static void ReadFile (string absolutepath, string filename, int index, File outpath) {try {BufferedReader bufreader = new BufferedReader (New InputStreamReader (new FileInputStream (Absolutepath), "gb2312"); Data stream Read File StringBuffer strbuffer = new StringBuffer (); String newstr = "I love you Too"; String oldstr = "I love You"; for (String temp = null; (temp = Bufreader.readline ()) = null; temp = null) {if ((Temp.indexof (OLDSTR)! =-1) && (Temp.indexof (oldstr)! = -1)) {//Determine if the current line has a character to be replaced temp = Temp.replace (oldstr, NEWSTR);//Replace here} Strbuffer.append (temp); Strbuffer.append (System.getproperty ("Line.separator")); Line break} bufreader.close (); if (outpath.exists () = = False) {//Check the output folder for presence, if not present first create outpath.mkdirs (); SYSTEM.OUT.PRINTLN ("The output folder was successfully created:" + Outpath); } printwriter PrintWriter = new PrintWriter (outpath + "\ \" + filename, "gb2312"); Replace after output file path Printwriter.write (strbuffer.tostring (). ToCharArray ()); Re-write Printwriter.flush (); Printwriter.close (); System.out.println ("+" + (index + 1) + "files" + Absolutepath + "successfully output to" + Outpath + "\" + Filena ME); } catch (Exception e) {e.printstacktrace (); } }}
Itmyhome
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java traverses all files under the folder and replaces the specified string