Replace the associated word in the file (a) with the file type txt

Source: Internet
Author: User

First of all, the specific implementation of the idea:

The first step: we need to get the information to modify the file, we can get the file's FileInputStream through the path of the file, that is, the file input stream, and then call InputStreamReader read the file input stream information, Saves read-in information to BufferedReader (BufferedReader reads text from the character input stream, buffering individual characters, providing efficient reading of characters, arrays, and rows. The flow information is then read through the ReadLine () function, which completes the first step and we can get the information of the file.

Second step: Can read the information of the file, we can use Matcher to match the word we want to replace, and then replace the word with appendreplacement (), and save the replaced string information,

Finally: Re-print the replaced file information to a new file, then see the code implementation:

Package com; Import Java.io.bufferedreader;import java.io.file;import java.io.fileinputstream;import java.io.FileOutputStream; Import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Java.util.regex.matcher;import Java.util.regex.Pattern; /** * * @author fishroad * @date August 17, 2015 PM 3:04:08 * */public class Test01 {/** * function: Java read content of TXT file * Step: 1 : Get file Handle First * 2: Get file handle as input a byte stream, need to read this input stream * 3: After reading to the input stream, you need to read the output of generating byte stream * 4: one line.     ReadLine ().                * Note: The exception needs to be considered * @param filePath */public static void Readtxtfile (String filePath) {try {                String encoding= "GBK";                File File=new file (FilePath);                String outstr;                    if (File.isfile () && file.exists ()) {//Determine if the file exists inputstreamreader read = new InputStreamReader ( New FileInputStream (file), encoding);//considering the encoding format BufferedReader BufferedReader = new Bu          Fferedreader (read);          String linetxt = null;                    StringBuffer sb = new StringBuffer ("");                        while ((Linetxt = Bufferedreader.readline ()) = null) {System.out.println (linetxt);                    Sb.append (linetxt+ "\ r \ n");                    } sb.append ("What I want to say is so you are just a good person!");                    outstr = Sb.tostring ();                    The word substitution method for calling a file is String changerstr = Tpreplaceword (OUTSTR);                    Read.close ();                    FileOutputStream out = new FileOutputStream ("f:/My files copy. txt");                    OutputStreamWriter write = new OutputStreamWriter (out);                    Write.write (CHANGERSTR);                    Write.flush ();        Write.close ();        }else{System.out.println ("The specified file cannot be found");            }} catch (Exception e) {System.out.println ("Error reading file contents");        E.printstacktrace ();     }    The public static string Tpreplaceword (String str) {/*stringbuffer strbuf = new StringBuffer (); Strbuf.append ("Ja VA is a generic term for the Java object-oriented programming language (hereinafter referred to as the Java language) and the Java platform introduced by Sun Microsystems Corporation. \ r "+" was co-developed by James Gosling and colleagues and was launched in 1995. \ r "+" Java was originally known as Oak, and was designed for embedded chips in consumer electronics in the 1991. \ r "+" was renamed Java in 1995 and redesigned to develop Internet applications. \ r "+" java-enabled HotJava browser (Java applet support) shows the charm of Java: \ r "+" cross-platform, dynamic web, Internet computing. \ r "+" Since then, Java has been widely accepted and promoted the rapid development of the web, commonly used browsers support Javaapplet. \ r "+" on the other hand, Java technology is constantly being updated. Since the advent of Java is very popular, rapid development, the C + + language to form a strong impact. \ r "+" in the global cloud computing and mobile Internet industry environment, Java has a significant advantage and broad prospects. \ r "+" 2010 Acquisition of Sun Microsystems by Oracle Corporation. \ r "); String a = strbuf.tostring (); *///generates the Pattern object and compiles a simple regular expression "java" Pattern p = pattern.compile ("java");// The Matcher () method of the pattern class is used to generate a Matcher object matcher m = P.matcher (str); StringBuffer sb = new StringBuffer (); int i = 0;//Use the Find () method to find the first matching object, boolean result = M.find ();//Use loops to find and replace all Java in the sentence Add to SB while (result) {i++;m.appendreplacement (SB, "hehe");//System.out.println ("+ i +" after the second match the content of SB is: "+ SB);//Continue to find the next match Object result = M. find ();} The last call to the Appendtail () method adds the remaining string after the last match to SB; M.appendtail (SB);        System.out.println ("M.appendtail (SB) after the final content of SB": \ r "+ sb.tostring ()); return sb.tostring ();}      public static void Main (String argv[]) {//The file information is the information about Java in the above strbuf String FilePath = "f:\\aaaaa.txt";//        "Res/";    Readtxtfile (FilePath); }           }


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Replace the associated word in the file (a) with the file type txt

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.