Search code examples
javafileprintwriter

Java: PrintWriter object does not output the text on my file?


I'm trying to print out the usernames of a certain program into a file but PrintWriter is not printing anything on my file. I've tried everything mentioned on stackOverFlow none of them worked.

Users Class

private File usersListFile;
private PrintWriter usersListPrintWriter;
private Scanner usersListScanner;

Constructor:

Users(){
    try {
        this.usersListFile = new File("D:\\Dairy\\usersList.txt");
        if(usersListFile.exists()){
            this.usersListPrintWriter = new PrintWriter(new BufferedWriter(new FileWriter("D:\\Dairy\\usersList.txt", true)));
            this.usersListScanner = new Scanner("D:\\Dairy\\usersList.txt");
        }
        else
            System.err.println("File does not exist !");
    }
    catch(Exception e){
        System.err.println("Error: Users Class!");                   
    }
}

Method:

public void addToUsersList(String username){
        usersListPrintWriter.print(username);           
    }

Main Method:

public static void main(String[] args) {

    Users usersObject = new Users();
    usersObject.addToUsersList("USERNAME");

    }

Solution

  • usersListPrintWriter is buffered, so you need to flush the data (as Alexandro mentioned too).

    You also likely will need to change the print into a println so newly added users are output on separate lines.

    Your Scanner will not work, since you're scanning the given string, not the file content. Use new Scanner(this.usersListFile) instead.

    You should also re-use your File object on the previous line: new FileWriter(this.usersListFile, true)

    And I would say that having a Writer and a Scanner open on the same file at the same time is a bad idea, if it even works. You should probably just load all the users into memory and close the scanner before opening the writer, unless you have