开发者

to read a double value from file in java

My file contains only 18.746786635311242 as a content and nothing else when I try to read that double number using code

FileInputStream fin = new FileInputStream("output");
        DataInputStream din = new DataInputStream(fin);
         f = din.readDouble();
        System.out.println(f);
        din.close();

and try to print f the value shows 1.3685694889开发者_运维知识库781536E-71


If it is text, you need to read ti as text, not binary. The simplest solution is to use a BufferedReader.

BufferedReader br = new BufferedReader(new FileReader("output"));
double d = Double.parseDouble(br);
br.close();

or use a Scanner.

Scanner scan = new Scanner(new File("output"));
double d = scan.nextDouble();
scan.close();


The decimals might be overflowing the size of a double on your system or only a certain number of bytes are being read (max that it can read probably 8) and then interpreting that as a double, try using

BigDecimal f = new BigDecimal(din.readLine());
System.out.println(f);

This should give you the desired result.


You could also try

Double d = new Double(din.readLine().trim());


Since DataInputReader.readLine() is actually deprecated, I'd do it like this:

FileInputStream fin = new FileInputStream("double.txt");
InputStreamReader isr = new InputStreamReader(fin);
BufferedReader br = new BufferedReader(isr);
BigDecimal f = new BigDecimal(br.readLine().trim());
System.out.println(f);
br.close();
isr.close();
fin.close();

Nonetheless, the key here is to actually use BigDecimal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜