java基础问题(求助)。。

snaillxc 2010-12-05 02:57:44
import java.io.*;
public class TestRandom
{
public static double []data;
public static double fileLength;
public static void getRandomNum()
{
int i;
try
{
System.out.println("请输入一个整数n:");
BufferedReader f=new BufferedReader(new InputStreamReader(System.in));
i=mb_getInt(f);
//System.out.println(i);
File file=new File("out.txt");
RandomAccessFile dfin=new RandomAccessFile(file,"rw");
double num;
//dfout.writeInt('0'+i);
//int length;
dfin.writeDouble(i*8+8);
for(int j=0;j<i;j++)
{
num=Math.random()*1000; //产生0-1000的双精度随机数
//dfout.writeDouble('0'+num);
dfin.writeDouble(num);
}
//dfout.close();

dfin.seek(0);
data=new double[i];
fileLength=dfin.readDouble();
for(int n=0;n<i;n++)
{
data[n]=dfin.readDouble();
}
dfin.close();
System.out.println("文件的长度是:"+fileLength+"字节,该数据保存在文件out.txt头部中!");
}

catch(IOException e)
{
//System.err.println("Exception!");
System.out.println("Exception");
//e.printStackTrace();
}
}
public static int mb_getInt(BufferedReader f)
{
try
{
String s=f.readLine();
int n=Integer.parseInt(s);
return n;
}
catch (Exception e)
{
return -1;
}
}
}

PS:这不是主程序。这只是用来生成n个双精度浮点数,为什么运行后,在dos窗口可以显示各精确的数据。但是打开out.txt里面全是乱码?求解??
...全文
176 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
vv404725784 2010-12-05
  • 打赏
  • 举报
回复
可以看一下源代码嘛,这里写到文件里的就是二进制的里的,
(八位的 二进制),可以考虑别的方法在文件里写吗
/**
* Converts the double argument to a <code>long</code> using the
* <code>doubleToLongBits</code> method in class <code>Double</code>,
* and then writes that <code>long</code> value to the file as an
* eight-byte quantity, high byte first. The write starts at the current
* position of the file pointer.
*
* @param v a <code>double</code> value to be written.
* @exception IOException if an I/O error occurs.
* @see java.lang.Double#doubleToLongBits(double)
*/
public final void writeDouble(double v) throws IOException {
writeLong(Double.doubleToLongBits(v));
}
一口三个汉堡 2010-12-05
  • 打赏
  • 举报
回复
字符编码的问题,jdk上写的。他用的是8个字节,所以可能和你机子上默认的字符编码不一样,所以出错了,我刚才试了几次,用字符串才成功了的。
writeDouble
public final void writeDouble(double v)
throws IOException使用 Double 类中的 doubleToLongBits 方法将双精度参数转换为一个 long,然后按八字节数量将该 long 值写入该文件,先定高字节。写入从文件指针的当前位置开始。
mengyalizuopeng 2010-12-05
  • 打赏
  • 举报
回复
代码格式化一下。。这样看着太累。。
  • 打赏
  • 举报
回复
因为直接写数据,数据格式没有转换为二进制字符。

建议这样写:

String trans = Double.toString(num)+"\n";
dfin.writeBytes(trans);
kaininghaha 2010-12-05
  • 打赏
  • 举报
回复
恩,刚刚接触,学习一下
config_man 2010-12-05
  • 打赏
  • 举报
回复
代码格式化一下。。这样看着太累。。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧