2

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");

    }

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

You are awesome! I was wondering what's wrong with my Scanner, Thank you very much!
@EJP I deliberately referred to usersListPrintWriter, not PrintWriter, since usersListPrintWriter is explicitly created with a BufferedWriter in the chain. You are however correct in implying that PrinWriter is also buffering, and so is FileWriter I believe. Changing answer back.
n that case it would be better to say 'both PrintWriter and BufferedWriter are buffered' in the answer. Variables aren't buffered.
1
public void addToUsersList(String username){
    usersListPrintWriter.print(username);           
    usersListPrintWriter.flush();
}

Then, when you don't need anymore your printwriter, call close().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.