簡體   English   中英

將數組寫入CSV文件-Java

[英]Writing an array to a CSV File - Java

我要寫入要在Excel中打開的CSV文件的數組中有24個元素。

當我運行程序時,它將在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方法中存在錯誤。 任何提示或幫助將不勝感激。 謝謝。

對於剛剛收聽的人...

將您的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. 除非您實際上打算將不同數量的元素寫入CSV文件,否則請從此函數中刪除count參數。 從您的主要方法來看,情況並非如此。

  2. 將for循環中的count更改為courseArray.length

然后,在您的main方法中,將調用更改為:

writeCSV(course2);

始終確保初始化變量,如有疑問,請使用調試器。 那可以幫助您發現這一點。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM