I have the following code
public static void main(String aed[]){
double d=17.3;
try{
DataOutputStream out=null;
out=new DataOutputStream(new BufferedOutputStream(new FileOutputStream("new.txt")));
out.writeDouble(d);
out.flush();
}catch(FileNotFoundException fnf){
fnf.printStackTrace();
}catch(IOException io){
io.printStackTrace();
}
}
Now I am writing this double value to a text file new.txt , but following value is getting in text file
@1LÌÌÌÌÍ
But when i use
out.writeUTF(""+d)
It works fine. Please explain the encoding that is going on here.
With
DataOutputStream
you are writing bytes, the bytes that represent a double value (which is a number value) and not the readable version of that number.Example:
int i = 8;
In binary i value is '0100' and that's the value that the computer manages.... But you don't want to write the bits '0100' because you want something to read, not it's value; you want the CHARACTER '8', so you must transform the double to character (to String is also valid because is readable)....
And that's what you are doing with ("" + d): transforming it to String.
Use Writer to write text files (BufferedWriter and FileWriter are available, check this for more details)