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()
returns true
then 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 tmpdir
as the parent directory. Then you test to see is tmpdir
is null
and create a directory. But you then proceed to use the File
object which STILL has a null
parent directory!!
You need to create the File
object AFTER checking tmpdir
and creating it if required.
Your approach dealing with tmpDir
is flawed. The file is getting created somewhere.
From the Javadocs for File(String, String)
:
If parent is null then the new File instance is created as if by invoking the single-argument File constructor on the given child pathname string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With