Creating csv file using java [closed]

2019-09-21 19:42发布

问题:

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