简体   繁体   English

在Java中读取CSV文件时出现NumberFormatException

[英]NumberFormatException when reading CSV file in java

I'm beginner in java and kinda stuck in these two problems so I'm trying to let the program read from a CSV file line by line. 我是Java的初学者,有点卡在这两个问题中,所以我试图让程序逐行从CSV文件读取。

So in the file I have first row as String and the column is double. 因此,在文件中,第一行为String,列为double。 So the problem is when it read first line It's reading the titles as double and it gives me an error. 所以问题是当它读取第一行时,它正在读取标题为双精度的字,这给了我一个错误。

By the way it is CSV file 顺便是CSV文件

The error i got are these below Exception in thread "main" java.lang.NumberFormatException: For input string: "CLOSE" This is first error 我得到的错误是在线程“ main”下的以下异常java.lang.NumberFormatException:对于输入字符串:“ CLOSE”这是第一个错误

Second error >> at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecima‌​l.java:1222) – 第二个错误>>在sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecima:l.java:1222)–

Third error >> at java.lang.Double.parseDouble(Double.java:510) 第三个错误>>在java.lang.Double.parseDouble(Double.java:510)

Forth error >>> at AlgorithmTrader.ReadInputData(AlgorithmTrader.java:63) 在AlgorithmTrader.ReadInputData(AlgorithmTrader.java:63)上出现第四次错误>>>

Fifth Error >> at AlgorithmTrader.Run(AlgorithmTrader.java:16) 第五错误>> at AlgorithmTrader.Run(AlgorithmTrader.java:16)

Last error >> SimpleAlgorithmTradingPlatform.main(SimpleAlgorithmTradingPl‌​atform.java:15) 最后一个错误>> SimpleAlgorithmTradingPlatform.main(SimpleAlgorithmTradingPlatform.java:15)

So the first row in the file has TIMESTAMP | 因此,文件的第一行具有TIMESTAMP | Close | 关闭| High | 高| Low | 低| open | 打开 volume and under each of those row there is numbers as double except volume has integer numbers 体积,在这些行的每一行下都有双倍的数字,但体积有整数

Your suggestion will appreciated. 您的建议将不胜感激。 Thanks 谢谢

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

public class AlgorithmTrader {

    public void Run() {

        ReadInputData();
    }

    public void ReadInputData() {

        // create object of scanner class for user input
        Scanner scan = new Scanner(System.in);
        // declare file name for input file
        String inputFileName = "";

        // input from user for input file
        System.out.print("Enter Input File Name: ");
        inputFileName = scan.nextLine();
        try {
            PrintWriter pw = new PrintWriter("output.csv");// to open the file

            // create a new file
            File file = new File(inputFileName);
            // create a new scanner object to read file
            Scanner readFile = new Scanner(file);

            // for each line data
            String line = "";

            line = readFile.nextLine();//skip the first line

            while (readFile.hasNextLine()) {

                readFile.nextLine();
                // pass file to scanner again
                readFile = new Scanner(file);

                ArrayList<String> list = new ArrayList<String>();

                // read stock data line by line

                while (readFile.hasNextLine()) {
                    // read line from file
                    line = readFile.nextLine();
                    // split line data into tokens
                    String result[] = line.split(",");

                    // variables to create a Stock object

                    String timestamp = result[0];
                    double close = Double.parseDouble(result[1]);
                    double high = Double.parseDouble(result[2]);
                    double low = Double.parseDouble(result[3]);
                    double open = Double.parseDouble(result[4]);
                    int volume = Integer.parseInt(result[5]);

                    // store data into ArrayList
                    list.add(readFile.next());
                    pw.print(list.add(readFile.next()));

                    Stock stock = new Stock(timestamp, close, high, low, open, volume);
                }// end of while to read file

                //close readFile object
                readFile.close();
                pw.close();//close file
            }
        } catch (FileNotFoundException e1) {

            System.out.println(" not found.\n");
            System.exit(0);
        } catch (IOException e2) {
            System.out.println("File can't be read\n");
        }
    }
}

I have another file Stock class 我还有另一个文件库存类

public class Stock {

    String timestamp;

    double close;
    double high;
    double low;
    double open;
    int volume;

    Stock(String t, double c, double h, double l, double o, int v) {
        timestamp = t;
        close = c;
        high = h;
        low = l;
        open = o;
        volume = v;
    }

    public void settimestamp(String t) {
        this.timestamp = t;
    }

    public void setclose(double c) {
        this.close = c;
    }

    public void sethigh(double h) {
        this.high = h;
    }

    public void setopen(double o) {
        this.open = o;
    }

    public void setvolume(int v) {
        this.volume = v;
    }

    public String gettimestamp() {
        return timestamp;
    }

    public double close() {
        return close;
    }

    public double high() {
        return high;
    }

    public int volume() {
        return volume;
    }
}

And The main method in another file as well 而且另一个文件中的main方法也是如此

import java.text.DecimalFormat;

public class SimpleAlgorithmTradingPlatform {

    public static void main(String[] args) {

        DecimalFormat fmt = new DecimalFormat("#0.00"); // to get the      DecimalFormat

        AlgorithmTrader test = new AlgorithmTrader();

        test.Run();
    }
}

You are you having NumberFormatException because here 您遇到NumberFormatException是因为这里

line = readFile.nextLine();//skip the first line 

you are not skipping first line. 不会跳过第一行。 You'd better use BufferedReader instead of Scanner after getting file name. 获取文件名后,最好使用BufferedReader而不是Scanner。 I have corrected you code a bit. 我已经更正了您的代码。

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class AlgorithmTrader {

    public void Run() {
        ReadInputData();
    }

    public void ReadInputData() {

        // create object of scanner class for user input
        Scanner scan = new Scanner(System.in);
        // declare file name for input file
        String inputFileName = "";

        // input from user for input file
        System.out.print("Enter Input File Name: ");
        inputFileName = scan.nextLine();

        // create a new file
        File csvFile = new File(inputFileName);
        String line;
        ArrayList<Stock> list = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {

            System.out.println("Reading file " + csvFile);

            System.out.println("Skipping title of the CSV file");
            // Skip first line because it is title
            br.readLine();

            System.out.println("Converting line to Stock");

            while ((line = br.readLine()) != null) {

                String result[] = line.split(",");
                String timestamp = result[0];
                double close = Double.parseDouble(result[1]);
                double high = Double.parseDouble(result[2]);
                double low = Double.parseDouble(result[3]);
                double open = Double.parseDouble(result[4]);
                int volume = Integer.parseInt(result[5]);

                list.add(new Stock(timestamp, close, high, low, open, volume));
            }

            System.out.println("Done");

        } catch (FileNotFoundException e1) {
            System.out.println(" not found.");
            System.exit(0);
        } catch (IOException e2) {
            System.out.println("File can't be read");
        }
    }
}

It would be nice to see a fictional example of the contents within your CSV file but please spare us any additional comments. 很高兴看到CSV文件中内容的虚构示例,但请不要给我们其他任何注释。 ;) ;)

It looks like your errors (and probably all of them) are most likely coming from your Stock Class. 看来您的错误(可能是所有错误)最有可能来自您的股票类别。 That's for another posted question however your getters and setters need attention. 这是另一个发布的问题,但是您的获取者和安装者需要注意。 Some are missing as well but perhaps this is by choice. 一些也丢失了,但是也许这是选择。

You should be able to carry out this task with one Scanner object and one while loop. 您应该能够使用一个Scanner对象和一个while循环来执行此任务。 Use the same Scanner object for User input and file reading, it's reinitialized anyways. 使用相同的Scanner对象进行用户输入和文件读取,无论如何都会对其进行初始化。

The code below is one way to do it: 下面的代码是一种实现方法:

ArrayList<String> list = new ArrayList<>();
// create object of scanner class for user input
// and File Reading.
Scanner scan = new Scanner(System.in);
// declare file name for input file
String inputFileName = "";
// input from User for input file name.
System.out.print("Enter Input File Name: ");
inputFileName = scan.nextLine();

String tableHeader = "";
try {
    // create a new file with PrintWriter in a 
    PrintWriter pw = new PrintWriter("output.csv"); 
    File file = new File(inputFileName);
    // Does the file to read exist?
    if (!file.exists()) {
        System.err.println("File Not Found!\n");
        System.exit(0);
    }   
    // create a new scanner object to read file
    scan = new Scanner(file);
    // for each line data
    String line = "";
    tableHeader = scan.nextLine();
    String newline = System.getProperty("line.separator");
    // Print the Table Header to our new file.
    pw.print(tableHeader + newline);

    while (scan.hasNextLine()) {
        line = scan.nextLine();
        // Make sure we don't deal with a blank line.
        if (line.equals("") || line.isEmpty()) {
            continue;
        }
        // split line data into a String Array.
        // Not sure if there is a space after 
        // comma delimiter or not but I'm guessing
        // there is. If not then remove the space.
        String result[] = line.split(", ");
        // variables to create a Stock object
        String timestamp = "";
        double close = 0.0;
        double high = 0.0;
        double low = 0.0;
        double open = 0.0;
        int volume = 0;

        // Make sure there are enough array elements 
        // from our split string to fullfil all our 
        // variables. Maybe some data is missing.
        int resLen = result.length;
        if (resLen > 0) {
            if (resLen >= 1) { timestamp = result[0]; }
            if (resLen >= 2) { close = Double.parseDouble(result[1]); }
            if (resLen >= 3) { high = Double.parseDouble(result[2]); }
            if (resLen >= 4) { low = Double.parseDouble(result[3]); }
            if (resLen >= 5) { open = Double.parseDouble(result[4]); }
            if (resLen >= 6) { volume = Integer.parseInt(result[5]); }
        }
        // store data into ArrayList.
        // Convert the result Array to a decent readable string.
        String resString = Arrays.toString(result).replace("[", "").replace("]", "");
        list.add(resString);
        // Print the string to our output.csv file.
        pw.print(resString + System.getProperty("line.separator"));

        //Stock stock = new Stock(timestamp, close, high, low, open, volume);
    }   
    //close file
    scan.close();
    pw.close();
} 
catch (IOException ex ){
    System.err.println("Can Not Read File!\n" + ex.getMessage() + "\n");
    System.exit(0);
}

// Example to show that the ArrayList actually 
// contains something....
// Print data to Console Window.
tableHeader = tableHeader.replace(" | ", "\t");
tableHeader = "\n" + tableHeader.substring(0, 10) + "\t" + tableHeader.substring(10);
System.out.println(tableHeader);
for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i).replace(", ", "\t"));
}

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

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