Ask coding questions

← Back to all posts
Inconsistent saving of text files in java
Scouprie (1)

I have provided my students with a saving function for text files in Java. In Replit, it always successfully saves a new file if one with its name does not exist. When using the function in another IDE (IntelliJ or Netbeans) it will save over existing files as expected. In Replit, for some students it successfully saves over existing files but for other students it does not. It simply does not make any change to the existing file.

Thoughts?

public static void saveList(String filename, ArrayList temp) {
        try {
            PrintWriter file = new PrintWriter(new FileWriter(filename));

            for (int i = 0; i < temp.size(); i++) {        
                file.println(temp.get(i));
            }
            file.close();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }// end saveStringList
Comments
hotnewtop
DynamicSquid (4928)

I think the inconsistencies could be from a person using your method multiple times.

Every time you use the method, you are creating a new FileWriter object to handle the same file:

PrintWriter file = new PrintWriter(new FileWriter(filename));

This means that there could be multiple FileWriter objects pointing to one file. Also, I think .close() has to be called on FileWriter in order to flush the file properly. So I think the problem is that there's multiple FileWriter objects pointing to one file, and none of their buffers are getting flushed.

Maybe you should just pass in the filename instead:

PrintWriter file = new PrintWriter(filename);
EpicGamer007 (1736)

You cant save files on replit. Files on replit are a bit weird. If you want to save data from a program, you have to use a database like ReplDB or another database. For the moment, you should ask your students to use their desktop ide (Eclipse, Intellij, or Netbeans).

CodeLongAndPros (1624)

@EpicGamer007 @Scouprie
All good ideas, but if you were really dedicated:

  • make a buffer
  • write the file io in there
  • compress it
  • Base64 encode it
  • dump it into repldb
  • ???
  • profit