Java 如何读取csv字段并将其转换回使用?

Java 如何读取csv字段并将其转换回使用?,java,csv,Java,Csv,我的问题是关于题目 日期时间类 import java.util.Date; class DateTime { private static long advance; // keeps tracks of any time advance private long time; public DateTime() // constructor { time = System.currentTimeMillis() + advan

我的问题是关于题目

日期时间类

    import java.util.Date;

    class DateTime {
    private static long advance; // keeps tracks of any time advance
    private long time;

    public DateTime() // constructor
    {
        time = System.currentTimeMillis() + advance;
    }

    public long getTime() {
        return time;
    }

    // advances date/time by specified days, hours and mins for testing purpose
    public static void setAdvance(int days, int hours, int mins) {
        advance = ((days * 24L + hours) * 60L) * 60000L;
    }

    public String toString() {
        long l = getTime();
        Date gct = new Date(l);
        return gct.toString();
    }

    public static String getCurrentTime() // returns current date/time
    {
        Date d = new Date(System.currentTimeMillis() + advance);
        return d.toString();
    }

    // returns difference in days
    public static int diffDays(DateTime d2, DateTime d1) {
        return (int) (1 + (d2.getTime() - d1.getTime()) / (24L * 60 * 60 * 1000));
    }
}

Vehicle class

    public class Vehicle {
    public enum State { A, S, H} 
    protected State status;
    protected int odo;
    protected double dailyRate;
    protected DateTime hiredDate;
    protected String vehicleID, hirerID, description;

    public Vehicle (String vehicleID, String description, double dailyRate, int odo) {
        this.vehicleID = vehicleID;
        this.description = description;
        this.dailyRate = dailyRate;
        this.odo = odo;
        status = State.A;
    }
    }
我将通过以下方式将其存储为csv文件格式:

vehicleID,desription,dailyRate,odo,hirerID,hiredDate
这是我的
readFile()
方法,我将从csv中读取并将其放回原处

    BufferedReader br = null;
    String line = "";
    String spliter = ",";
    Vehicle.State status;
    String vehicleID, description, hirerID, cID, cName, cPhone;
    DateTime hiredDate;
    double dailyRate = 0.0, discountRate = 0.0;
    int odo = 0, freeMilAllowance = 0, serviceLength = 0, 
            odoFromLastService = 0, pastMileage = 0;

    try {

        br = new BufferedReader(new FileReader(filePath));
        while ((line = br.readLine()) != null) {

if (fileType == Type.V) {
                 vehicleID = file[0];
                 description = file[1];
                try {
                     dailyRate = Double.parseDouble(file[2]);
                } catch (NumberFormatException nfe) {
                  System.err.println(nfe);
                }
                try {
                     odo = Integer.parseInt(file[3]);
                } catch (NumberFormatException nfe) {
                  System.err.println(nfe);
                }
                status = Vehicle.State.valueOf(file[4]);
                hirerID = file[5];
                hiredDate = file[6]
                // Construct a vehicle and add into list
                Vehicle v = new Vehicle (vehicleID, description, dailyRate, odo);
                v.setStatus(status);
                v.setHirerID(hirerID);
                v.setHiredDate(hireDate);
                vehicleList.add(v);
如何从字符串转换并将其解析为
DateTime
对象,以便在程序中使用

如何从字符串转换并将其解析为DateTime对象,以便在程序中使用

我无法100%确定要转换的列中的值。我假设它是某种日期时间字符串。为此,我倾向于使用Jodatime
DateTimeFormat
。例如:

DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/YYYY");
DateTime current = formatter.parseDateTime(valueString);
这将生成一个
org.joda.time.DateTime
对象,该对象不应与您的
DateTime
相混淆。然后可以调用
current.getMillis()
以获取自epoch以来的毫秒数


此外,要解析CSV文件,可能需要使用类似my的CSV库。还有很多其他的例子。

下面是一个你如何阅读的例子:

假设,格式为:vehicleID、description、dailyRate、odo、hirrid、hiredDate

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CSVReader {

    public static void main(String[] args) {

        String csvFile = "/.../csv/vehicle.csv";
        String line = "";
 String cvsSplitBy = ",";
        DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/YYYY");
        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {

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

                // use comma as separator
                String[] vehicle = line.split(cvsSplitBy);

                System.out.println("Vehicle [id= " + vehicle[0] + " , 

..., +"hiredDate=" + vehicle[5] + "]");
// And here get data
DateTime dd = formatter.parseDateTime(vehicle[5]);


            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.csvreader.CsvWriter;

    public class CsvWriterAppendExample {


        public static void main(String[] args) {

        String outputFile = "vehicle.csv";
        // before we open the file check to see if it already exists
        boolean alreadyExists = new File(outputFile).exists();

        try {
            // use FileWriter constructor that specifies open for appending
            CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');

            // if the file didn't already exist then we need to write out the header line
            if (!alreadyExists)
            {
                csvOutput.write("vehicleID");
                csvOutput.write("desription");
                csvOutput.write("dailyRate");
                csvOutput.write("odo");
                csvOutput.write("hirerID");
                csvOutput.write("hiredDate");
                csvOutput.endRecord();
            }
            // else assume that the file already has the correct header line

            // write out a few records

            csvOutput.write("any vehicleID");
            csvOutput.write("... Bruce");
            csvOutput.write("12");
            csvOutput.write("dailyRate");
            csvOutput.write("od");
            csvOutput.write("hiererID");
            csvOutput.write("data");
            csvOutput.endRecord();

            csvOutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}