I struggled for hours with this because the file is in a directory on a server that doesn't allow access from netbeans. Thus for reasons explained above .isFile(), .exists() etc don't work for me.
My workaround was this:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.nio.file.Path;
public class CSVReader
{
private boolean fileExists = false;
public void readCSVFile(Path path)
{
try
{
System.out.println("reading csv file");
BufferedReader br = new BufferedReader(new fileReader(path.toString()));
//netbeans complains that br is never read but doesn't stop anything working
setFileExists(true);
}
catch (FileNotFoundException ex)
{
System.out.println("file does not seem to exist. New file will be created");
}
}
}
my csvWriter method then uses the boolean (fileExists) to create a new file and then either write the header as well as the values, or just append the values to the end of the file.
I am using openCSV and also setting the 'append' flag to true if the file already exists
import com.opencsv.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
public class WriteToCSV
{
public void createCSVfile(Path path, boolean fileExists)
{
FileWriter outputFile = null;
CSVWriter w = null;
String[] data =
{
"col1 val", "col2 value", "col3 value", "col4 value"
};
try
{
File f = new File(path.toString());
if (fileExists)
{
System.out.println("file exists");
outputFile = new FileWriter(f, true); //append flag set
w = new CSVWriter(outputFile);
}
else
{
System.out.println("file doesn't exist");
outputFile = new FileWriter(f); //append flag not set. Data will be overwritten
w = new CSVWriter(outputFile);
w.writeNext(COLUMN_HEADERS);
}
w.writeNext(data);
w.close();
System.out.println("file created at " + path);
}
catch (IOException ex)
{
System.out.println("unable to create new file " + path.getFileName() + ". " + ex);
System.exit(Thread.currentThread().getStackTrace()[1].getLineNumber());
}
finally
{
try
{
outputFile.close();
}
catch (IOException ex)
{
System.out.println("unable to close csv file " + ex);
System.exit(Thread.currentThread().getStackTrace()[1].getLineNumber());
}
}
}
}
canRead
,canWrite
, andcanExecute
to check for that.