Vlad Otrocol
Vlad Otrocol

Reputation: 3172

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");
        }
        
    }
}

Upvotes: 1

Views: 375

Answers (5)

ynka
ynka

Reputation: 1497

        File file = new File("numbers.txt");        
        BufferedReader reader = null;
        double[] a = new double[3];
        double[] b = new double[3];

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            if ((text = reader.readLine()) != null) {
                String [] nos = text.split("[ ,]");
                for(int i=0;i<nos.length/2;i++){
                    a[i]=Double.valueOf(nos[2*i]).doubleValue();
                    b[i]=Double.valueOf(nos[2*i+1]).doubleValue();
                }
            }

            for(int i=0;i<3;i++){
                    System.out.println(a[i]);
                    System.out.println(b[i]);
           }

        } catch (FileNotFoundException e) {            
        } catch (IOException e) {            
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {            
            }
        }

Upvotes: 0

Dan Hardiker
Dan Hardiker

Reputation: 3053

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[].

Upvotes: 5

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

EDIT Oops, this is not what you want. I don't see the logic in the way of constructing the arrays you want.


  1. Read the content from the file
  2. Split the string on spaces. Create for each element of the splitted array an array.

    String input = "0.12,4.56 2,5 0,0.234";
    String parts[] = input.split(" ");
    double[][] data = new double[parts.length][];
    
  3. Split each string on commas.

  4. Parse to a double.

    for (int i = 0; i < parts.length; ++i)
    {
         String part = parts[i];
         String doubles[] = part.split(",");
         data[i] = new double[doubles.length];
         for (int j = 0; j < doubles.length; ++j)
         {
             data[i][j] = Double.parseDouble(doubles[j]);
         }
    }
    

Upvotes: 0

duffymo
duffymo

Reputation: 308733

Reading from a file in Java is easy:

http://www.exampledepot.com/taxonomy/term/164

Figuring out what to do with the values once you have them in memory is something that you need to figure out.

You can read it one line at a time and turn it into separate values using the java.lang.String split() function. Just give it ",|\\s+" as the delimiter and off you go:

public class SplitTest {
    public static void main(String[] args) {
        String raw = "0.12,4.56 2,5 0,0.234";
        String [] tokens = raw.split(",|\\s+");
        for (String token : tokens) {
            System.out.println(token);
        }
    }
}

Upvotes: 0

Rogel Garcia
Rogel Garcia

Reputation: 1915

You will have to read the complete line.

String line = "0.12,4.56 2,5 0,0.234"; //line variable will recieve the line read

Then.. you split the line on the commas or the spaces

String[] values = line.split(" |,");

This will result in an array like this: [0.12, 4.56, 2, 5, 0, 0.234]

Now, just reorganize the contents between the two order arrays.

Upvotes: 0

Related Questions