Search code examples
javafilefileoutputstream

hash symbol is displayed in file in java


 File f = new File("even.txt");
 FileOutputStream fo = new FileOutputStream(f);
 int a = 2;
 fo.write(a);
 fo.close();

Whenever I run this program and open the "even.txt" file, all I'm able to see is a hash symbol in the file. This doesn't happen when I work with a string.

 File f = new File("even.txt");
 FileOutputStream fo = new FileOutputStream(f);
 String s = "2";
 byte b[] = s.getBytes();
 fo.write(b);
 fo.close();

I don't understand why this happens.


Solution

  • What you have to understand is

    int a = 2;
    fo.write(a); //This line write the byte 0x02 to the inputstream because that is the binary representation of the digit 2
    
    String s = "2";
    byte b[] = s.getBytes();
    fo.write(b); //This one write 0x32 to the inputstream because that is the ascii respresentation of the character "2" which is return by getBytes() from the string class
    

    you can check the difference between the two file the code generate in an hex editor