The following code does not always create the file.
As far as I noticed, the first time this code has run, though no exception is thrown and createdFileSucceeded == true, the file doesn’t get created.
I run the code on Windows, java 6.
Any input could be helpful
File file = new File(tmpDir, fileName);
try {
if (tmpDir == null) {
String environmentHomePath // = somePath;
tmpDir = new File(environmentHomePath, "SampleDumps");
if (! tmpDir.exists() || ! tmpDir.isDirectory()) {
boolean mkdirSucceeded = tmpDir.mkdir();
if (! mkdirSucceeded) {
throw new IOException("Failed creating directory: '" + tmpDir.getAbsolutePath() + "'");
}
}
}
if (file.exists()) {
boolean deleteFileSucceeded = file.delete();
if (! deleteFileSucceeded) {
throw new IOException("Unable to delete pre existing sample file: '" + fileName + "'");
}
}
boolean createFileSucceeded = file.createNewFile();
if (! createFileSucceeded) {
throw new IOException("Unable to create sample file: '" + fileName + "'");
}
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
StringBuilder sb = new StringBuilder("something...");
bw.write(sb.toString());
bw.flush();
}
catch (IOException ioe) {
log.warn("Unable to file invalid sample to file: '" + fileName + "'", ioe);
}
finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
log.warn("Unable to close Writer to file: '" + fileName + "'", e);
}
}
else if (fw != null) {
try {
fw.close();
} catch (IOException e) {
log.warn("Unable to close Writer to file: '" + fileName + "'", e);
}
}
}
If
file.createNewFile()returnstruethen a file was created.The most likely explanation that the file is being created, but not in the place where you are expecting. I expect that you are using a relative pathname for the file …
Looking more carefully at your code and your comment, I think that is exactly what is happening. Take a look at the way that you create the temporary directory. You first construct the file using
tmpdiras the parent directory. Then you test to see istmpdirisnulland create a directory. But you then proceed to use theFileobject which STILL has anullparent directory!!You need to create the
Fileobject AFTER checkingtmpdirand creating it if required.