Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As proposed in <a href="https://stackoverflow.com/a/822166/644766">the accepted answer</a> to <a href="https://stackoverflow.com/questions/822150/modify-a-txt-file-in-java">a similar question</a>:</p> <blockquote> <p>open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file.</p> </blockquote> <p>Based on your implementation, something similar to:</p> <pre><code>import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class ReplaceFileContents { public static void main(String[] args) { new ReplaceFileContents().replace(); } public void replace() { String oldFileName = "try.dat"; String tmpFileName = "tmp_try.dat"; BufferedReader br = null; BufferedWriter bw = null; try { br = new BufferedReader(new FileReader(oldFileName)); bw = new BufferedWriter(new FileWriter(tmpFileName)); String line; while ((line = br.readLine()) != null) { if (line.contains("1313131")) line = line.replace("1313131", ""+System.currentTimeMillis()); bw.write(line+"\n"); } } catch (Exception e) { return; } finally { try { if(br != null) br.close(); } catch (IOException e) { // } try { if(bw != null) bw.close(); } catch (IOException e) { // } } // Once everything is complete, delete old file.. File oldFile = new File(oldFileName); oldFile.delete(); // And rename tmp file's name to old file name File newFile = new File(tmpFileName); newFile.renameTo(oldFile); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload