将数组写入CSV文件 - Java

时间:2014-04-01 20:10:22

标签: java arrays csv

我在数组中有24个元素,我希望写入要在Excel中打开的CSV文件。

当我运行程序时,它会在我的Netbeans项目文件夹中创建一个CSV文件。但是,当我打开CSV文件时 - 它是空白的。

在我的main方法中,我向用户显示数组,然后调用writeCSV方法,如下所示:

    //show the user the sorted array
    System.out.println( "The sorted array is: ");
    for ( int i=0; i<24; i++)      
        System.out.println( "\t" + course2[i].toString() );

    //write the data from the duplicate array to a CSV file
    System.out.println("\nWriting data from Course array to CSV File.");
    writeCSV(course2, count);

writeCSV方法粘贴在下面:

    //write from duplicate array of courses to a CSV file
    public static void writeCSV(Course[] courseArray, int count) throws Exception {

    //create a File class object and give the file the name employees.csv
    java.io.File courseCSV = new java.io.File("courses.csv");

    //Create a Printwriter text output stream and link it to the CSV File
    java.io.PrintWriter outfile = new java.io.PrintWriter(courseCSV);

    //Iterate the elements actually being used
    for (int i=0; i < count ; i++) {
        outfile.write(courseArray[i].toCSVString());

    }//end for

    outfile.close();
    } //end writeCSV()

上面的writeCSV方法调用toCSVString方法,该方法在我创建的名为Course的类中定义。我在下面贴了这个方法:

// method to return properties as a CSV string on one line
//public String toCSVString(Course c){
public String toCSVString() {
    String record = campus + ","
                  + course + ","
                  + section + ","
                  + crn + ","
                  + credits + ","
                  + time + ","
                  + days + "\n";

    return record;
} //end toCSVString()

我的代码运行完美,直到我必须将数组写入CSV文件。这是在创建空白CSV文件时。这让我相信我的toCSVString方法或者我认为的writeCSV方法中有错误。任何提示或帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

对于刚刚收听的人......

将writeCSV方法更改为:

//write from duplicate array of courses to a CSV file
public static void writeCSV(Course[] courseArray) throws Exception {

    //create a File class object and give the file the name employees.csv
    java.io.File courseCSV = new java.io.File("courses.csv");

    //Create a Printwriter text output stream and link it to the CSV File
    java.io.PrintWriter outfile = new java.io.PrintWriter(courseCSV);

    //Iterate the elements actually being used
    for (int i=0; i < courseArray.length ; i++) {
        outfile.write(courseArray[i].toCSVString());

    }//end for

    outfile.close();
} //end writeCSV()
  1. 从这个函数中删除count参数,除非你真的 打算在CSV文件中写入不同数量的元素。 从你的主要方法来看,情况并非如此。

  2. 将for循环中的count更改为courseArray.length

  3. 然后,在您的main方法中,将调用更改为:

    writeCSV(course2);
    

    始终确保初始化变量,如有疑问,请使用调试器。这可以帮助你发现这一点。

    希望这有帮助。