1 Attachment(s)
Writing integers to a file
Hello,
I am simply trying to print a random integer to a text file. However when I open up the text it just shows= square shapes and not the numbers. I attached the .txt file
Code :
public void writefile(int amountLines, File filename) throws IOException
{
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
Random generator = new Random();
for (int i = 0; i < amountLines; i++)
{
writer.write( generator.nextInt(amountLines -1) + 1);
writer.newLine();
}
if (writer != null)
{
writer.flush();
writer.close();
}
}
Re: Writing integers to a file
The reason for this is that the BufferedWriter has a method called write(int c) which takes an int. If you pass an int into this method it will automatically try to figure out what character that int represents and write that character to the stream instead of actually writing the int itself.
To write the int to the stream you should do this.
Code :
writer.write([b]String.valueOf([/b]generator.nextInt(amountLines -1) + 1[b])[/b]);
See the String.valueOf(). This will turn the int into a string and the BufferedWriters write(String str) method will be used instead.
// Json
Re: Writing integers to a file
Thanks that solved it. So the BufferedWriter wrtie(int c) method tries to look up the corresponding ASCII value of the int?
Re: Writing integers to a file
technically Unicode, but yes, it's the same idea.