【问题标题】:How to I split date and time that are on the same column and store them in an ArrayList?如何拆分同一列上的日期和时间并将它们存储在 ArrayList 中?
【发布时间】:2019-05-23 02:49:45
【问题描述】:

我正在使用“JFreeChart”创建数据可视化程序,但在使用 BufferedReader 从 CSV 文件中读取数据时遇到问题。在 CSV 文件中,我将日期和时间存储在同一列中。我知道我必须使用 " " 函数来分隔它们,但我不知道该怎么做。

我试过到处找,但我无法找到它。我需要被推上正确的轨道。

//This is part of my Data Class

private int millis;
    private int stamp;
    private int light; 
    private double temp;
    private double vcc;
    private Time theTime;
    private Date theDate;


//This is part of another class

public class CSVreader {

    private List<Data> dataList = new ArrayList<Data>();
    private String path;

    public List<Data> getDataList() {
        return dataList;
    }
    public String getPath() {
        return path;
    }
    public void setPath(String path) {
        this.path = path;
    }

    public void readCSV() throws IOException{ 

        BufferedReader in = new BufferedReader (new FileReader(path));

        String line = in.readLine();

        while(line != null) {

            Data d = new Data();

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

            int millis = Integer.parseInt(splits[0]);
            int stamp = Integer.parseInt(splits[1]);
            int light = Integer.parseInt(splits[2]);
            double temp = Double.parseDouble(splits[3]);
            double vcc = Double.parseDouble(splits[4]);

            d.setMillis(millis);
            d.setStamp(stamp);
            d.setLight(light);
            d.setTemp(temp);
            d.setVcc(vcc);

            dataList.add(d);

        }

        }

}

最终结果应该是所有数据都将在一个数组列表中,我可以调出这些结果并从列表中使用 JFreeChart 创建一个图表。

【问题讨论】:

  • 您的代码中的问题到底出在哪里 - 您在阅读哪些列时遇到问题?共享 CSV 文件的示例行可能会有所帮助。另外,请注意您正在跳过splits[2] - 这是故意的吗?
  • 这是 CSV 的示例行; 2000, 1273010255, 2010/5/4 21:57:35, 333, 78.32, 3.92
  • 我无法读取日期/时间,即“2010/5/4 21:57:35”
  • private Time theTime; 这是习惯吗? @A.uddin

标签: java csv arraylist bufferedreader


【解决方案1】:

根据您的评论,将 splits 数组中的 3 个元素按空格 " " 分隔符拆分

String dateTime[] = splits[2].split(" ");
String date = dateTime[0];
String time = dateTime[1];

但我可以看到dateTime 的数据类型不同

private Time theTime;
private Date theDate;

如果Datejava.util.Date,您可以使用SimpleDateFormat 将字符串转换为Date

DateFormat formatter = new SimpleDateFormat("yyyy/dd/mm");
Date date = formatter.parse(testDate);

【讨论】:

    【解决方案2】:

    根据您阅读“2010/5/4 21:57:35”日期/时间的评论, 更简单的方法可以使用Joda Time Library

    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/M/d HH:mm:ss");
    DateTime dt = formatter.parseDateTime("2010/5/4 21:57:35");
    

    然后可以从Datetime获取日期时间值:

    String time = dt.toString("HH:mm:ss");
    String date = dt.toString("yyyy/M/d");
    

    但我看到数据类型不是字符串,如果你想把它解析成日期数据类型可以这样做:

    Date date = dt.toDate();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 2020-02-29
      相关资源
      最近更新 更多