Creating csv file using java [closed]

99封情书 提交于 2019-12-25 19:39:44

问题


I'm currently working on creating a csv file in Java. I have the below code but doesn't seem to work.

String newFileName = "Temp" + fileName;
File newFile = new File(newFileName);

I don't know what else to do. Do I need to specify the file path? Please help. Thanks.


回答1:


java.io.File is just an

An abstract representation of file and directory pathnames.

you have to use FileWriter/PrintWriter/BufferedWriter to create an actual physical file on the disk.

Sorta like this:

String newFileName = "Temp" + fileName;
File newFile = new File(newFileName);
BufferedWriter writer = new BufferedWriter(new FileWriter(newFile));



回答2:


Use commons-csv to write the data. From the 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();



回答3:


Take a look at Basic I/O tutorial. Special attention to Buffered Streams part.

You don't need to specify the full path of the file.




回答4:


Creating File instances won't create the file on the file system. You're just getting a handle or reference to it. You would have to add contents to the file and write the file, so that the file actually gets written to the disk in the location you specify.

Read Reading, Writing, and Creating Files for more information. Also, before getting into NIO, as the other post mentions, read IO Streams



来源:https://stackoverflow.com/questions/15529749/creating-csv-file-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!