简体   繁体   English

将数字从文本文件读取到Java中的ArrayList中

[英]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? 您将使用Array还是ArrayList,为什么? Anything else I've found online is too complicated to understand for my level of experience with Java. 对于我的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. 这是到目前为止,我正在测试它,看看我是否在正确执行ArrayList。 It keeps printing an empty ArrayList that is just two brackets. 它一直在打印一个空的ArrayList,它只是两个括号。

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. 在第一个while()循环中获取每行值时,您可以使用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(","); 正如@Justin Jasmann所说,您有逗号分隔的值,因此从技术上讲它们不仅仅是double Double.parseDouble(String s)值,为什么不将它们读取为String,然后在通过使用string.split(",");获得逗号分隔值之后使用Double.parseDouble(String s)解析它们Double.parseDouble(String s) 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();
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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