0

I have a little problem in file writing in Java.

I've created a new file using File f = new File(path); and a BufferedWriter that writes to that file. And one int i = 1; Now the buffered writer (file writer) shall write the int i to the file but it doesn't, It writes CUBES! Like this one ■. And When Scanner reads the file, it reads that cube, and an error happens,

Here is an example:

int i = 1;
File f = new File(path);
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(i);

int b = 0;
Scanner s = new Scanner(new FileReader(f));
b = s.nextInt();
//end

But for some reason it writes a cube ■ not number 1, and that's why scanner cant read it.

Any ideas why is this happening? -Thank for helping. ■

  • 1
    Did you bother to *read* the javadoc of the [`BufferedWriter.write(int c)`](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html#write-int-) method you are calling? It says: *Writes a single character.* It doesn't write the number using base-10 decimals. For that, you should use a `PrintWriter` and call [`print(int i)`](https://docs.oracle.com/javase/8/docs/api/java/io/PrintWriter.html#print-int-). – Andreas Dec 11 '16 at 10:27
  • @Andreas Bonus question: If you actually wanted to write a base 10 number, which character code would you use (not that I am recommending this)? – Tim Biegeleisen Dec 11 '16 at 10:30

1 Answers1

0

The write method doesn't write the interger value as text but the integer is interpreted as a character code.

You should better use a PrintWriter, which is more comfortable. With it you can use the same print methods as in System.out.

PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(f)));
writer.print(i);

You should also be aware, that you are implicitly use the default platform encoding, which is Cp1252 (Windows ANSI) for Windows and usually UTF-8 for Linux. To avoid unexpected behaviour it is recommended to always set the character encoding explicitly. Then you end up with:

PrintWriter writer = new PrintWriter(new BufferedWriter(
    new OutputStreamWriter(new FileOutputStream(f), "UTF-8")));

This is a litte bit more complex but the file encoding is under your control.

vanje
  • 10,180
  • 2
  • 31
  • 47
  • Yes, that's what I need. It works, awesome. May I know why did i get a negative vote? And thank's for helping!!! –  Dec 11 '16 at 16:19