0

I'm trying to update a value in a text file. In my text file I have the value 100 which I'm trying to add 1 too. Whenever I run the code though, it doesn't print anything or write into the text file.

public static void main(String[] args) throws IOException {  
    try {
      File myObj = new File("C:\\Users\\proto\\OneDrive\\Documents\\atmDep.txt");
      Scanner myReader = new Scanner(myObj);  
      FileWriter myWriter = new FileWriter("C:\\Users\\proto\\OneDrive\\Documents\\atmDep.txt");
      while (myReader.hasNextLine()) {
        int data = myReader.nextInt();
        
        int num = 1;
        myWriter.write(data + num);
        System.out.println(data);
        
      }
      myReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
mike mane
  • 1
  • 2
  • You can not read from and write to the same file at the same time. You either need to read the whole file first and then write it by moving the FileWriter code to be after the scanner is closed, or you need to write to a different file and replace the old one with the new one once it's closed. – sorifiend May 03 '22 at 02:19
  • @sorifiend Or use RandomAccessFile. – GhostCat May 03 '22 at 10:52
  • 1
    Yes, RandomAccessFile is the way to go. One thing too mention in case you weren’t are - what if instead of adding 1 you add 901 - that makes the value that you will want to write is 1001, which is one character LONGER than the 100 that you are overwriting. If your application allows that, that is something you will have to deal with - what you will probably want to do is shift the rest of the file by that one character, and that is something YOU will have to do (read the rest of the file, write the 1001 then writing the rest of that file); no libraries will do that for you. – racraman May 03 '22 at 11:46

0 Answers0