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.
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));
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();
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.
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