1

I have some problems regarding reading the double input from text file

i am writing a progran that can read the input fron a file which contains number like this

  • 3.4 5.0 12
  • 1.3 8.2 6
  • 0.8 9.1 2.3

anyone got some idea or tips please..??

package Test;

import java.io.*;
import java.util.*;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;

public class readfileVector {
public static void main(String[] args){
    try{
        readDataFromFile();
    }catch(IOException ex){
        ex.printStackTrace();
    }


}
public static void readDataFromFile() throws IOException{
    double a, b, c;

    FileInputStream fis = null;
    try{
        fis = new FileInputStream(new File("D:\\Pro1\\vector.inp.txt"));
        DataInputStream dis = new DataInputStream(fis);

        a = dis.readDouble();
        b = dis.readDouble();
        c = dis.readDouble();

        System.out.println("double:" + a + "; double:" + b + ";double:" + c );
    }catch(IOException ex){
        ex.printStackTrace();
    }finally{
        if(fis != null)
            fis.close();
    }
}

} I'm trying to do this

2 Answers2

1
String stringValue = new Scanner( new File("myDoubles.txt") ).useDelimiter("\\A").next();

// split string by any whitespace
String[] doublesAsStrings = stringValue.split("\\s+");

for( int i = 0; i < doublesAsStrings.length; i++ )
    double val = Double.parseDouble( doublesAsStrings[i] );

You get the idea.

Source:How do I create a Java string from the contents of a file?

Community
  • 1
  • 1
Joey Clover
  • 756
  • 5
  • 14
1

You can read your file using scanner something like this:

    Scanner s = new Scanner(new File(<your file>));

    while(s.hasNextDouble()){
          a = s.nextDouble();
          b = s.nextDouble();
          c = s.nextDouble();

          System.out.println("double:" + a + "; double:" + b + ";double:" + c );

    }

Hope this helps.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33