我目前正在用Java創建一個csv文件。我有下面的代碼,但似乎沒有工作。使用java創建csv文件
String newFileName = "Temp" + fileName;
File newFile = new File(newFileName);
我不知道還能做些什麼。我需要指定文件路徑嗎? 請幫忙。謝謝。
我目前正在用Java創建一個csv文件。我有下面的代碼,但似乎沒有工作。使用java創建csv文件
String newFileName = "Temp" + fileName;
File newFile = new File(newFileName);
我不知道還能做些什麼。我需要指定文件路徑嗎? 請幫忙。謝謝。
java.io.File只是一個
的文件和目錄路徑名的抽象表示。
你必須使用FileWriter/PrintWriter/BufferedWriter創建磁盤上的實際物理文件。
有點兒像這樣:
String newFileName = "Temp" + fileName;
File newFile = new File(newFileName);
BufferedWriter writer = new BufferedWriter(new FileWriter(newFile));
您也可以使用File API中的[File.createNewFile()](http://docs.oracle.com/javase/6/docs/api/java/io/File.html#createNewFile())。 – jahroy 2013-03-20 18:32:54
看看Basic I/O tutorial。特別注意緩衝流部分。
您不需要指定文件的完整路徑。
創建File
實例不會在文件系統上創建文件。你只是得到一個句柄或引用它。您必須將內容添加到該文件並寫入該文件,以便該文件實際上被寫入您指定位置的磁盤。
閱讀Reading, Writing, and Creating Files瞭解更多信息。另外,在進入NIO之前,如其他帖子提及,請閱讀IO Streams
我想創建一個空文件。 – user2026615 2013-03-20 17:03:26
@ user2026615 - 您也可以使用File API中的File.createNewFile()。當你想使用Java類時,你應該總是查閱文檔。你可以通過搜索「_Java 7 File_」找到任何類的文檔(例如:File)。如果你點擊第一個鏈接,你會看到大量的文檔描述了你可以用File對象做的所有事情 – jahroy 2013-03-20 18:49:51
使用commons-csv來寫入數據。來自test code:
final FileWriter sw = new FileWriter("myfile.csv");
final CSVPrinter printer = new CSVPrinter(sw, format);
for (int i = 0; i < nLines; i++) {
printer.printRecord(lines[i]);
}
printer.flush();
printer.close();
是的,你需要指定文件路徑。 – 2013-03-20 16:52:03
由於缺乏知識,不值得投票太多。 – asgs 2013-03-20 16:54:43
嘗試閱讀文檔。您可以通過搜索「Java 7文件」並單擊第一個結果來查找File API的文檔。 – jahroy 2013-03-20 16:54:56