regex - Find and replace in Java using regular expression without changing file format -


i've code replaces 10:a 12:a in text file called sample.txt. also, code i've changing file format, shouldn't. can please let me know how same using regular expression in java doesn't change file format? file has original format below
10:a
14:saxws
after executing code outputs 10:a 14:saxws.

import java.io.*;      import java.util.*;        public class filereplace {     list<string> lines = new arraylist<string>();     string line = null;     public void  doit()     {         try         {             file f1 = new file("sample.txt");             filereader fr = new filereader(f1);             bufferedreader br = new bufferedreader(fr);             while ((line = br.readline()) != null)             {                 if (line.contains("10:a"))                     line = line.replaceall("10:a", "12:a") + system.lineseparator();                 lines.add(line);             }             fr.close();             br.close();              filewriter fw = new filewriter(f1);             bufferedwriter out = new bufferedwriter(fw);             for(string s : lines)                  out.write(s);             out.flush();             out.close();         }         catch (exception ex)         {             ex.printstacktrace();         }     }     public static void main(string[] args)     {         filereplace fr = new filereplace();         fr.doit();     } } 

it looks os or editor not able print correctly line separators generated system.lineseparator(). in case consider

  • reading content of entire file string (including original line separators), - replacing part interested in
  • and writing replaced string file

you can using code:

path file = paths.get("sample.txt");  //read bytes file (they include bytes representing used line separtors) byte[] bytesfromfile = files.readallbytes(file);  //convert themm string string textfromfile = new string(bytesfromfile, standardcharsets.utf_8);//use proper charset  //replace need (line separators stay same) textfromfile = textfromfile.replaceall("10:a", "12:a");  //write data file files.write(file, textfromfile.getbytes(standardcharsets.utf_8), standardopenoption.create); 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -