Search code examples
javafileio

Read from a file in Java


Does anybody know how to properly read from a file an input that looks like this:

0.12,4.56 2,5 0,0.234

I want to read into 2 arrays in Java like this:

a[0]=0.12
a[1]=2
a[2]=0;

b[0]=4.56
b[1]=5
b[2]=0.234

I tried using scanner and it works for input like 0 4 5 3.45 6.7898 etc but I want it for the input at the top with the commas.

This is the code I tried:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class IFFTI {
    public static int size=0;
    public static double[] IFFTInputREAL= new double[100];
    public static double[] IFFTInputIMAG= new double[100];
    
    static int real=0;
    static int k=0;

    public static void printarrays(){
        for(int k=0;k<size;k++){
        System.out.print(IFFTInputREAL[k]);
        System.out.print(",");
        System.out.print(IFFTInputIMAG[k]);
        System.out.print("\n");
        }
    }

    public static void readIFFT(String fileName){

        try {
            Scanner IFFTI = new Scanner(new File(fileName));        
            while (IFFTI.hasNextDouble()) {
                if(real%2==0){
                    IFFTInputREAL[k] = IFFTI.nextDouble();
                    real++;
                }
                else{
                    IFFTInputIMAG[k] = IFFTI.nextDouble();
                real++;
                k++;}
            }
            try{
            size=k;
            }catch(NegativeArraySizeException e){}
        } catch (FileNotFoundException e) {
            System.out.println("Unable to read file");
        }
        
    }
}

Solution

  • I think this will do what you want:

    String source = "0.12,4.56 2,5 0,0.234";
    
    List<Double> a = new ArrayList<Double>();
    List<Double> b = new ArrayList<Double>();
    
    Scanner parser = new Scanner( source ).useDelimiter( Pattern.compile("[ ,]") );
    while ( parser.hasNext() ) {
        List use = a.size() <= b.size() ? a : b;
        use.add( parser.nextDouble() );
    }
    
    System.out.println("A: "+ a);
    System.out.println("B: "+ b);
    

    That outputs this for me:

    A: [0.12, 2.0, 0.0]
    B: [4.56, 5.0, 0.234]
    

    You'll obviously want to use a File as a source. You can use a.toArray() if you want to get it into a double[].