I want to write the numbers to a file. The programs runs without any errors but when I open the file that I wrote to, the contents of the file is something like “!”#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ“.
I cross-checked by reading the contents of the file using FileInputStream and printing the contents. The IDE prints the desired output but the integers in the file are not stored in readable form.
Can anyone tell me why the integers are not populating in the file as intended?
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
try{
FileOutputStream fos = new FileOutputStream("Exercise_19.txt");
for(int i = 0;i<=200; i++){
fos.write((int)i);
}
fos.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}
fos.write(int) writes a byte using the lowest 8-bits of the integer.
if you want to write text to a file, a simpler option is to use PrintWriter (note PrintWriter can use FileOutputStream so it can be done, but you really have to know what you are doing.)