我在数组中有24个元素我正在写入要在Excel中打开的CSV文件。将数组写入CSV文件 - Java
当我运行我的程序时,它会在我的Netbeans项目文件夹中创建一个CSV文件。但是,当我打开CSV文件时 - 它是空白的。
在我的主要方法,我向用户示出阵列,然后调用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方法中有一个错误,我相信。任何提示或帮助将不胜感激。谢谢。
你确定count设置正确而不是0吗?这将与您的问题兼容。 – Drunix
为什么使用替代变量,例如'count'而不是数组的内置大小'courseArray.length'?我把它看作是一个函数参数,但不知道它的用途是否真的是你需要/想要的? –
@Drunix在我的主要方法中,我首先定义int count = 0; – zhughes3