简体   繁体   中英

How to replace multiple occurences of a string in a text file with a variable entered by the user and save all to a new file?

 public static void main(String args[])
     {
     try
         {
         File file = new File("input.txt");
         BufferedReader reader = new BufferedReader(new FileReader(file));
         String line = "000000", oldtext = "414141";
         while((line = reader.readLine()) != null)
             {
             oldtext += line + "\r\n";
         }
         reader.close();
         // replace a word in a file
         //String newtext = oldtext.replaceAll("drink", "Love");

         //To replace a line in a file
         String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");

         FileWriter writer = new FileWriter("input.txt");
         writer.write(newtext);writer.close();
     }
     catch (IOException ioe)
         {
         ioe.printStackTrace();
     }
 }

}

A couple suggestions on your sample code:

  1. Have the user pass in old and new on the command line (ie, args[0] and args 1 ).
  2. If it's sufficient to do this a line at a time, it's going to be much more efficient to read a line, replace old -> new, then stream it out.

Also check out StringUtils and IOUtils , which may make your life easier in this case.

最简单的是String.replace(oldstring,newstring)或String.replaceAll(regex,newString)函数,您可以只读取一个文件并将替换文件写入新文件中(或者如果需要的话,可以逐行执行)关于文件大小)。

After reading your last comment - that's a totally different story... the preferred solution would be to parse the css file into an object model (like DOM), apply the changes there and serialize the model to css afterwards. It's much easier to find all color attributes in DOM and change them compared to doing the same with search and replace.

I've found some CSS parser in the wild wild web, but none of them looked like being capable of writing CSS files.

If you wanted to replace the color names with search and replace, you'd search for 'color:<colorname>' and replace it with 'color:<youHexColorValue>'. You may have to do the same for 'color:"<colorname>"', because the color name can be set in double quotes (another argument for using a CSS parser..)

String.replaceAll() is the easiest way to do it. Just read the complete CSS file into one String, replace all as suggested above and write the new String to the same (or a temporary) file (first).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM