I\'m having an issue getting this to work. It takes in a string which consists of several pieces of information put together. However, when I try to write the String to a f
You have to have folders created first. But you can't call file.mkdirs() - you need to call file.getParentFile().mkdirs() - otherwise, you will create a folder with the name of the file (which will then prevent you from creating a file with the same name).
I'll also mention that you should check the result code of mkdirs(), just in case it fails.
And though you didn't ask for it, I'll still mention that you don't need to call createNewFile() (your FileWriter will create it).
and, just for thoroughness, be sure to put your file.close() in a finally block, and throw your exception (don't just print it) - here you go:
void writeToFile(String input) throws IOException{
File file = new File("C:\\WeatherExports\\export.txt");
if (!file.getParentFile().mkdirs())
throw new IOException("Unable to create " + file.getParentFile());
BufferedWriter out = new BufferedWriter(new FileWriter(file,true));
try{
out.append(input);
out.newLine();
} finally {
out.close();
}
}