0

I'm trying to overwrite the contents in a text file (as a part of an encoding program), and whenever I run the code the file becomes empty, but the contents are back there when I restart my computer.
Why is this happening, and how can I fix this?

fileScan = new Scanner(f);
fileWriter = new FileWriter(f);

while (fileScan.hasNext()) {
        //store current line
        curLine = fileScan.nextLine();
        curLineParsed = new char[curLine.length()];
        //parse into characters
        for (int i = 0; i < curLine.length(); i++)
            curLineParsed[i] = curLine.charAt(i);
        //reset new line
        newLine = "";

        //ENCODING ONE LINE
        //repeat for every code character
        for (int i = 0; i < code[0].length; i++) {
            //go through each character in the line
            for (int j = 0; j < curLineParsed.length; j++) {
                //if the character in process equals to the current character in line
                if (code[0][i] == curLineParsed[j]) {
                    //replace character
                    curLineParsed[j] = code[1][i];
                }
            }
        }

        //store it in a new string
        for (int i = 0; i < curLineParsed.length; i++)
            newLine += curLineParsed[i];
        System.out.println(newLine);

        //REPLACING ENCODED LINE WITH ORIGINAL
        fileWriter.write(newLine+"\n");
    }
    fileWriter.close();
Chris K
  • 5
  • 5
  • 1
    It's awfully suspicious that you're both reading from and writing to the same file in interleaving fashion. The effect is probably not what you expect. Either read everything you want to read before writing anything, or write to a separate file and afterward replace the original. – John Bollinger Jan 21 '17 at 22:33
  • OP, it doesn't seem that you're flushing the buffer that the FileWriter writes to. When your computer restarts, your OS most likely flushes the buffer itself. – Jacob G. Jan 21 '17 at 22:37
  • 1
    @JacobG. Closing causes flushing. – user207421 Jan 21 '17 at 23:27
  • @EJP Ah, then that's a weird bug the OP has then. Maybe he can try using a PrintWriter instead and see if it makes a difference. – Jacob G. Jan 22 '17 at 00:06
  • I don't suppose it's possible that the file is one that gets written by the system at startup? – John Bollinger Jan 22 '17 at 00:21

0 Answers0