【发布时间】:2014-04-01 20:10:22
【问题描述】:
我希望将数组中的 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 方法调用了我创建的名为 Course 的类中定义的 toCSVString 方法。我把这个方法贴在下面:
// 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 方法中有错误。任何提示或帮助将不胜感激。谢谢。
【问题讨论】:
-
您确定计数设置正确而不是 0?这将与您的问题兼容。
-
为什么要使用
count等替代变量而不是数组的内置大小courseArray.length?我将它视为一个函数参数,但想知道它的预期用途是否真的是您需要/想要的? -
@Drunix 在我的 main 方法中,我首先定义 int count=0;
-
@RyanJ 我使用 writeCSV(course2,course2.length) 调用了 writeCSV 方法,它工作正常。谢谢!
-
... 这解释了为什么您的文件为空(除非您稍后将其设置为正确的值)