简体   繁体   中英

Reading numbers from a text file into an ArrayList in Java

Can anyone show me a basic guideline for how to do this sort of thing? Would you use an Array or an ArrayList, and why? Anything else I've found online is too complicated to understand for my level of experience with Java. The file is a simple text file with seven decimal values per line, and contains three lines. Here is what I have so far and am just testing it to see if I'm doing the ArrayList properly. It keeps printing an empty ArrayList that is just two brackets.

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

public class SalesAnalysis 
{
    public static void main (String[] args) throws FileNotFoundException
    {

        Scanner salesDataFile = new Scanner(new File("SalesData.txt"));

        ArrayList<Double> salesData = new ArrayList<Double>();

        while(salesDataFile.hasNextDouble())
        {
            salesData.add(salesDataFile.nextDouble());
        }
        salesDataFile.close();

        System.out.println(salesData);

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

public class SalesAnalysis
{
    public static void main (String[] args) throws FileNotFoundException
    {

        Scanner salesDataFile = new Scanner(new File("SalesData.txt"));

        ArrayList<Double> salesData = new ArrayList<Double>();

        while(salesDataFile.hasNextLine()){
            String line = salesDataFile.nextLine();

            Scanner scanner = new Scanner(line);
            scanner.useDelimiter(",");
            while(scanner.hasNextDouble()){
                salesData.add(scanner.nextDouble());
            }
            scanner.close();
        }

        salesDataFile.close();

        System.out.println(salesData);
    }
}

Read lines from file, then for each file get doubles using Scanner.

And for per line basis, you can just create Lists for every line, like:

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

public class SalesAnalysis
{
    public static void main (String[] args) throws FileNotFoundException
    {

        Scanner salesDataFile = new Scanner(new File("SalesData.txt"));

        while(salesDataFile.hasNextLine()){
            String line = salesDataFile.nextLine();

            ArrayList<Double> salesData = new ArrayList<Double>();

            Scanner scanner = new Scanner(line);
            scanner.useDelimiter(",");
            while(scanner.hasNextDouble()){
                salesData.add(scanner.nextDouble());
            }
            scanner.close();

            System.out.println(salesData);
        }

        salesDataFile.close();

    }
}

As you are getting per line values inside first while() loop, you can do whatever with line.

        // number of values in file
        int totalNumValues = 0;
        // total sum
        double totalSum = 0;

        while(salesDataFile.hasNextLine()){
            String line = salesDataFile.nextLine();

            ArrayList<Double> salesData = new ArrayList<Double>();

            // total values in this line
            int numValuesInLine = 0;
            // sum in this line
            double sumLine = 0;

            Scanner scanner = new Scanner(line);
            scanner.useDelimiter(",");
            while(scanner.hasNextDouble()){
                  double value = scanner.nextDouble();
                  sumLine = sumLine + value;
                  numValuesInLine++;
                  totalNumValues++;
                  totalSum = totalSum + value;
            }
            scanner.close();

            System.out.println(salesData);
        }

I'd do something like this:

    Scanner salesDataFile = new Scanner(new File("SalesData.txt"));

    ArrayList<ArrayList< double > > salesData = new ArrayList<>();

    while(salesDataFile.hasNextLine() )
    {
        String stringOfNumbers[] = salesDataFile.nextLine().split(",");
        ArrayList< double > aux = new ArrayList<>( stringOfNumbers.length );
        for( int i = 0; i < stringOfNumbers.length; ++i )
           aux.get(i) = Double.parseDouble( stringOfNumbers[i] );
        //... Perform your row calculations ...
        salesData.add( aux );
    }
    salesDataFile.close();

    System.out.println(salesData);

As @Justin Jasmann said, you have comma separated values, so technically they are more than just double values, why not read them as String and then parse them using Double.parseDouble(String s) after you have your comma separatad value by using string.split(","); on every line.

This is what you are looking for,

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


public class FileRead {


    public static void main(String args[])
    {
        try{
            // Open the file that is the first 
            FileInputStream fstream = new FileInputStream("textfile.txt");

            // Use DataInputStream to read binary NOT text.
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

            String strLine;
            List<Double> saleNumbers= new ArrayList<Double>();

            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
                // Add number from file to list 
                saleNumbers.add( parseDecimal(strLine)); 
            }
            //Close the input stream
            in.close();

            System.out.println(saleNumbers);
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    public static double parseDecimal(String input) throws NullPointerException, ParseException{
          if(input == null){
            throw new NullPointerException();
          }

          input = input.trim();

          NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
          ParsePosition parsePosition = new ParsePosition(0);
          Number number = numberFormat.parse(input, parsePosition);

          if(parsePosition.getIndex() != input.length()){
            throw new ParseException("Invalid input", parsePosition.getIndex());
          }

          return number.doubleValue();
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM