Creating csv file using java [closed]

2019-09-21 19:14发布

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.

4条回答
戒情不戒烟
2楼-- · 2019-09-21 19:40

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

查看更多
Explosion°爆炸
3楼-- · 2019-09-21 19:51

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));
查看更多
倾城 Initia
4楼-- · 2019-09-21 19:56

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();
查看更多
够拽才男人
5楼-- · 2019-09-21 20:01

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.

查看更多
登录 后发表回答