title: How can I write to a specific line number in a txt file in Java
body: <p>I'm currently writing my project for school in which requires me to read and write to txt files. I can read them correctly but I can only write to them at the end from an appended FileWriter. I would like to be able to overwrite things in my txt files on line numbers by first deleting the data on the line and then writing in the new data. I attempted to use this method...</p>
  
  <pre><code>public void overWriteFile(String dataType, String newData) throws IOException
  {
      ReadFile file = new ReadFile(path);
      RandomAccessFile ra = new RandomAccessFile(path, "rw");
      int line = file.lineNumber(path, dataType);
      ra.seek(line);
      ra.writeUTF(dataType.toUpperCase() + ":" + newData);
  }
  </code></pre>
  
  <p>but I believe that the seek method moves along in bytes rather than line numbers. Can anyone help. Thanks in advance :)</p>
  
  <p>P.S. the file.lineNumber method returns the exact line that the old data was on so I already have the line number that needs to be written to.</p>
  
  <p>EDIT: Soloution found! Thanks guys :) I'll post the soloution below if anyone is interested</p>
  
  <pre><code>public void overWriteFile(String dataType, String newData, Team team, int dataOrder) throws IOException
  {
      try
      {
          ReadFile fileRead = new ReadFile(path);
          String data = "";
          if(path == "res/metadata.txt")
          {
              data = fileRead.getMetaData(dataType);
          }
          else if(path == "res/squads.txt")
          {
              data = fileRead.getSquadData(dataType, dataOrder);
          }
          else if(path == "res/users.txt")
          {
              data = fileRead.getUsernameData(dataType, dataOrder);
          }
          else if(path == ("res/playerdata/" + team.teamname + ".txt"))
          {
              //data = fileRead.getPlayerData(dataType, team.teamname, dataOrder);
          }
          BufferedReader file = new BufferedReader(new FileReader(path));
          String line;
          String input = "";
          while((line = file.readLine()) != null)
          {
              input += line + '\n';
          }
          input = input.replace(dataType.toUpperCase() + ":" + data, dataType.toUpperCase() + ":" + newData);
          FileOutputStream out = new FileOutputStream(path);
          out.write(input.getBytes());
      }
      catch(Exception e)
      {
          System.out.println("Error overwriting file: " + path);
          e.printStackTrace();
      }
  }
  </code></pre>