程序每次运行时都会将标题添加到CSV文件中

时间:2017-09-21 18:15:39

标签: java header export-to-csv

我在一年前为Java编程编写了这段代码。它是一个基本的食物日志控制台应用程序,可以创建CSV文件,并且可以在创建后附加用户的输入。我遇到了一个我无法解决的问题。我在一段时间内没有做太多编程,但我对解决方案很好奇。问题是每次程序运行时,它都会在CSV中插入另一个标题。我只希望它在初始创建时插入,如果文件已经存在,则跳过。

我最初的想法是if if(file.exists()== true){剩余代码块};在'try'块中,但它根本不写标题。

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FoodLogWriter {

private static final String COMMA_DELIMITER = ",";
private static final String NEW_LINE_SEPARATOR = "\n";
private static final String FILE_HEADER = "Date,Food Time,Food Item,Calories,Carbohydrates,Sugar,Protein,Fiber,Total Fat";
private static Scanner kb;

public static void writeFoodLog(String fileName, File file) throws IOException {

    List<FoodLog> list = new ArrayList<FoodLog>();
    FoodLogApp app = new FoodLogApp();

    kb = new Scanner(System.in);
    String Dinput;
    String FTinput;
    String FIinput;
    double CALinput;
    double CARBinput;
    double Sinput;
    double Pinput;
    double TFinput;
    double Finput;

    int i = 0;

    while (i < 1000) {

        System.out.print("Enter the date: ");
        Dinput = kb.next();

        System.out.print("Enter the food time: ");
        FTinput = kb.next();

        System.out.print("Enter the food item: ");
        FIinput = kb.next();

        System.out.print("Enter the calories: ");
        CALinput = kb.nextDouble();

        System.out.print("Enter the carbohydrates: ");
        CARBinput = kb.nextDouble();

        System.out.print("Enter the sugar: ");
        Sinput = kb.nextDouble();

        System.out.print("Enter the protein: ");
        Pinput = kb.nextDouble();

        System.out.print("Enter the fiber: ");
        Finput = kb.nextDouble();

        System.out.print("Enter the total fat: ");
        TFinput = kb.nextDouble();

        list.add(app.createFoodLog(Dinput, FTinput, FIinput, CALinput, CARBinput, Sinput, Pinput, Finput, TFinput));

        System.out.println("");
        System.out.print("Do you have another item to input? ");
        String response = kb.next();
        System.out.println("");

        if (response.equalsIgnoreCase("no")) {

            app.printFoodLog(list);
            break;

        } else {
            i++;
        }

        kb.nextLine();

    }

    FileWriter fileWriter = null;

    try {

        fileWriter = new FileWriter(fileName, true);

        if (file.exists() == false) {
            fileWriter.write(FILE_HEADER.toString());
        }
        fileWriter.append(NEW_LINE_SEPARATOR);

        for (FoodLog FL : list) {
            fileWriter.append(String.valueOf(FL.getDate()));
            fileWriter.append(COMMA_DELIMITER);
            fileWriter.append(String.valueOf(FL.getFoodTime()));
            fileWriter.append(COMMA_DELIMITER);
            fileWriter.append(String.valueOf(FL.getFoodItem()));
            fileWriter.append(COMMA_DELIMITER);
            fileWriter.append(String.valueOf(FL.getCalories()));
            fileWriter.append(COMMA_DELIMITER);
            fileWriter.append(String.valueOf(FL.getCarbohydrates()));
            fileWriter.append(COMMA_DELIMITER);
            fileWriter.append(String.valueOf(FL.getSugar()));
            fileWriter.append(COMMA_DELIMITER);
            fileWriter.append(String.valueOf(FL.getProtein()));
            fileWriter.append(COMMA_DELIMITER);
            fileWriter.append(String.valueOf(FL.getFiber()));
            fileWriter.append(COMMA_DELIMITER);
            fileWriter.append(String.valueOf(FL.getTotalFat()));
            fileWriter.append(NEW_LINE_SEPARATOR);
        }

        System.out.println("CSV file was created successfully.");

    } catch (Exception e) {
        System.out.println("Error in FoodLogWriter.");
        e.printStackTrace();
    } finally {

        try {
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            System.out.println("Error while flushing/closing file writer.");
            e.printStackTrace();
        }
    }

}

}

3 个答案:

答案 0 :(得分:1)

以下是其余的课程:

public class FoodLog {

private String Date;
private String FoodTime;
private String FoodItem;
private double Calories;
private double Carbohydrates;
private double Sugar;
private double Fiber;
private double Protein;
private double TotalFat;

public FoodLog(String Date, String FoodTime, String FoodItem, double Calories, double Carbohydrates, double Sugar,
        double Fiber, double Protein, double TotalFat) {

    // super();
    this.Date = Date;
    this.FoodTime = FoodTime;
    this.FoodItem = FoodItem;
    this.Calories = Calories;
    this.Carbohydrates = Carbohydrates;
    this.Sugar = Sugar;
    this.Fiber = Fiber;
    this.Protein = Protein;
    this.TotalFat = TotalFat;

}

public String getDate() {
    return Date;
}

public void setDate(String date) {
    Date = date;
}

public String getFoodTime() {
    return FoodTime;
}

public void setFoodTime(String foodTime) {
    FoodTime = foodTime;
}

public String getFoodItem() {
    return FoodItem;
}

public void setFoodItem(String foodItem) {
    FoodItem = foodItem;
}

public double getCalories() {
    return Calories;
}

public void setCalories(double calories) {
    Calories = calories;
}

public double getCarbohydrates() {
    return Carbohydrates;
}

public void setCarbohydrates(double carbohydrates) {
    Carbohydrates = carbohydrates;
}

public double getSugar() {
    return Sugar;
}

public void setSugar(double sugar) {
    Sugar = sugar;
}

public double getFiber() {
    return Fiber;
}

public void setFiber(double fiber) {
    Fiber = fiber;
}

public double getProtein() {
    return Protein;
}

public void setProtein(double protein) {
    Protein = protein;
}

public double getTotalFat() {
    return TotalFat;
}

public void setTotalFat(double totalFat) {
    TotalFat = totalFat;
}

public String toString() {
    return "FoodLog [Date = " + Date + ", Food Time = " + FoodTime + ", Food Item = " + FoodItem + ", Calories = "
            + Calories + ", Carbohydrates = " + Carbohydrates + ", Sugar = " + Sugar + ", Fiber = " + Fiber
            + ", Protein = " + Protein + ", Total Fat = " + TotalFat + "]";

}

}

import java.io.File;
import java.io.IOException;
import java.util.List;

public class FoodLogApp {

public static void main(String[] args) throws IOException {

    File file = new File("FoodLog.csv");
    String fileName = System.getProperty("user.home") + "/FoodLog.csv";
    FoodLogWriter.writeFoodLog(fileName, file);

}

public FoodLog createFoodLog(String Date, String FoodTime, String FoodItem, double Calories, double Carbohydrates,
        double Sugar, double Fiber, double Protein, double TotalFat) {

    return new FoodLog(Date, FoodTime, FoodItem, Calories, Carbohydrates, Sugar, Fiber, Protein, TotalFat);
}

public void printFoodLog(List<FoodLog> list) {

    for (FoodLog FL : list) {

        System.out.println("===========================================");
        System.out.println("Food Time : " + FL.getFoodTime());
        System.out.println("Food Item : " + FL.getFoodItem());
        System.out.println("Calories : " + FL.getCalories());
        System.out.println("Carbohydrates : " + FL.getCarbohydrates());
        System.out.println("Sugar : " + FL.getSugar());
        System.out.println("Protein : " + FL.getProtein());
        System.out.println("Fiber : " + FL.getFiber());
        System.out.println("Total Fat : " + FL.getTotalFat());
        System.out.println("===========================================");
        System.out.println("");         
    }

}

}

答案 1 :(得分:1)

我认为您的问题源于您在决定采取哪些操作之前尝试确定实际文件是否存在的方式(写入标头与否)。

在FoodLogApp#main中,每次运行时都会创建一个新文件(FoodLog.csv),然后传递FoodLogWriter#writeFoodLog。此文件此时作为实例变量创建并存在于JVM的内存中,检查是否存在导致问题的原因(因为此时它始终返回true)。

我建议您尝试以适当的方式检查文件是否以任何方式保留。也就是说,您需要执行I / O操作以确定文件路径(fileName变量)中是否存在文件。

最简单的方法是使用java .nio包。首先使用Paths.get(“file_path”)创建Path对象。然后使用Files.exists()检查给定路径上是否存在实际文件。

我想这可以解决你的问题。等着听它是否有效。

答案 2 :(得分:0)

你的问题在这里:

File file = new File("FoodLog.csv");
String fileName = System.getProperty("user.home") + "/FoodLog.csv";

变量文件取决于您执行java程序的位置(因为您使用的是相对路径而不是绝对路径), fileName 不是。因此,如果您在/ home / youruser /中执行,它将起作用,但如果您在另一个文件夹中执行,例如/ home / youruser / project /, file 将是“/家用/ youruser /项目/ FoodLog.csv。”

我建议您只更改订单并使用相同的变量:

String fileName = System.getProperty("user.home") + "/FoodLog.csv";
File file = new File(fileName);