Question

I have something like

int userChoice;
System.out.println("Enter your choice");
userChoice = userInput.nextInt(); //Scanner stuffs written already

Let's say the user chooses 0.

When I try to use BufferedWriter and write into a text file.

I get \00 being written to the file instead of 0.

Below are my codes..

try {

    BufferedWriter output = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream("salt.txt", true)));
    output.write(userChoice);
    output.close();
} catch (IOException e) {
    e.printStackTrace();
}

So how do I make it that it writes '0' to the file rather than '\00'

Was it helpful?

Solution

I would probably prefer to use a PrintWriter, but you should be able to do something like this -

// output.write(userChoice);
output.write(String.valueOf(userChoice));

OTHER TIPS

When you use write(int c), it interprets the integer as a character (like an ASCII value). Try converting userChoice into a String when writing it.

output.write(Integer.toString(userChoice));
output.write("" + userChoice);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top