我有以下代码
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();
}
}
现在我正在将这个 double 值写入文本文件 new.txt ,但以下值正在进入文本文件
@1LÌÌÌÌÍ
但是当我使用时
out.writeUTF(""+d)
效果很好。 请解释一下这里发生的编码。
最佳答案
在java中通常有两类变量,即引用类型和原始类型。
您的原始类型包括 int、double、byte、char、boolean、long、short 和 float。它们存储一个值,并在内存中用 unicode 16 位整数表示。
引用类型保存存储位置和对某些对象的引用。 ( string/UTF 是引用类型)因此可以看到实际值
二进制文件并不意味着由您读取,而是由程序读取,该程序将以正确的形式和顺序获取值,并且您使用的方法应仅用于写入二进制文件(.dat)以各自的形式(int、double 等)保存实际数据值。写入文本文件 (.txt) 时,应仅写入字符串。
写入文本文件:
try{
PrintWriter write=new PrintWriter("your filepath",true);
write.println("whatever needs to be written");
write.close();
}
catch(FileNotFoundException){
}
阅读:
Scanner read;
try{
read=new Scanner(new FileReader("your path"));
while(read.hasNext()){
System.out.println(read.nextLine);
}
read.close();
}
catch(FileNotFoundException e){
}
关于java - DataOutputStream 的 writeDouble() 方法以编码形式将数据写入文本文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30749317/