Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You're trying to read and write to the same file at the same time. While there may be a way of getting that to work, it's going to be fiddly.</p> <p>I suggest you read from file A and write to file B - and if you want to effectively replace the input file, then you can do that with a sequence of moves and deletes at the end.</p> <p>A few other suggestions:</p> <ul> <li>You should have try/finally blocks to close both the input and the output at the end.</li> <li>You don't need to use a <code>DataInputStream</code> - you're not using anything from it. Just wrap the input stream directly.</li> <li>I suggest you specify the encoding explicitly both for input and output rather than trusting the default encoding. (I wish <code>FileWriter</code> and <code>FileReader</code> accepted encodings in their constructors.)</li> <li>It's more robust to use <code>OutputStreamWriter</code> (or something similar) rather than <code>PrintWriter</code> - currently you're not going to detect if anything goes wrong when you're writing.</li> </ul> <p>So something like this:</p> <pre><code>// Ideally have this as a constant somewhere. Charset utf8 = Charset.forName("UTF-8"); BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream(inputFile), utf8); try { try { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputFile), utf8); String line; while ((line = reader.readLine()) != null) { if (!line.contains(name)) { writer.write(line); writer.newLine(); } } } finally { writer.close(); } } finally { reader.close(); } // Now if you want to shift files around, do it here </code></pre> <p>It's a shame that Java makes this so fiddly with the try/finally blocks. Oh for C#'s <code>using</code> statements...</p>
    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.
    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