APpending a file with an Integer(Question Inside)
Hello,
I want to fiqure why this simple code dose not work. I want to append data to an existing file but it has to be a number not a String.
I am still trying to learn so if it's a simple mistake I'm sorry. The following code writes a random number to a text file. I am making an educated guess that it's reading it as binary and in some shape form or fashion 50 equals 2 or something in binary. How do I get to just to write 50 at the end of the file. I know I can use the formatter class but that doesn't have a method for appending my data.
Re: APpending a file with an Integer(Question Inside)
Note that you are using a FileWriter and a BufferedWriter, and thus anything written to this file with any type of Writer *must* be a String. Also the file is a text file, so you really have no choice -- you *must* write a String and only a String to this file. To not do so makes no sense at all.
Re: APpending a file with an Integer(Question Inside)
Okay, I understand what you're saying. Is it at all possible,to convert my number to a string and insert it in the file. After that read it back in as a String and convert it as a integer, so then I can treat it as number. I have tried this using the scanner method and it throws me an exception. Please respond back.
Thanks
Re: APpending a file with an Integer(Question Inside)
Yes, ints can be easily changed to String via the String.valueOf(...) method. And int Strings can be read in with a Scanner, if done properly, or as a String and then converted to int via Integer.parseInt(...).
Re: APpending a file with an Integer(Question Inside)
This is what I got i tried but i still having trouble
It throws a number format exception
What am I doing wrong here.
Re: APpending a file with an Integer(Question Inside)
If it throws a NumberFormatException, then you're trying to parse something that's not a number into a number. Solution: don't do that. Only parse a number String.
Re: APpending a file with an Integer(Question Inside)
Then I am confused on how to proceed. How can I store " dos.writeUTF(50);" and change it to a int?