Search code examples
javafileio

Java text file not updating before opening


So for a school project I need to save user account details in a text file, and if you login the program has to read from the text file to see if the user exists.

Now the writing and reading works, but my problem is that the contents of the text file don't update until I open the file in eclipse. After I open the file I can see the new content suddenly appear in the file.

This is my code right now:

        String path = context.getRealPath("/");
        path = path.substring(0, path.length() - 71);
        path = path + "\\v2iac14\\src\\main\\resources\\accountIDs.txt";

        File file = new File(path);

        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fOut = new FileWriter(file, true);
        fOut.append("e:" + username + ";p:" + password + ";i:" + id + ";c:-----;");
        fOut.flush();
        fOut.close();

And how I read the file:

    InputStream inputStream = getClass().getClassLoader().getResourceAsStream("accountIDs.txt");
    String result = null;
    try {
        result = IOUtils.toString(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;

I already tried multiple methods of writing to the file but the problem stays the same..


Solution

  • The way your getting your filepath isn't the same, I'm pretty sure you're not writing the file you trying to read later.

    String path = context.getRealPath("/");
    path = path.substring(0, path.length() - 71);
    path = path + "\\v2iac14\\src\\main\\resources\\accountIDs.txt";  
    

    You might probaby be better to keep the same path construction in both functions.
    Don't forget to mutualized the code !

    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path);