title: How to replace a specific line in a file using Java?
body: <p>How do I write over a specific line in a text file using FileWriter and PrintWriter? I don't want to have to make a new file every time.</p>
  
  <p>Edit: Can I just cycle through the file, get the length of the String at the indicated line number, and then use that length to backspace once I get to that line (to delete the String), and write in the new data?</p>
  
  <pre><code>public static void setVariable(int lineNumber, String data) {
      try { 
          // Creates FileWriter. Append is on.
          FileWriter fw = new FileWriter("data.txt", true);       
  
          PrintWriter pw = new PrintWriter(fw);       
  
          //cycles through file until line designated to be rewritten is reached
          for (int i = 1; i &lt;= lineNumber; i++) {     
              //TODO: need to figure out how to change the append to false to overwrite data
              if (i == lineNumber) {
                  pw.println(data);
                  pw.close();
              } else {          
                  // moves printwriter focus to next line (doesn't overwrite)
                  pw.println(""); 
              }
          } 
      }
  }
  </code></pre>