Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java file.createNewFile file not created and no exceptions thrown

Tags:

java

io

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);
  }
}
}
like image 264
Jasmin Meg Avatar asked Apr 01 '12 15:04

Jasmin Meg


2 Answers

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.

like image 167
Stephen C Avatar answered Oct 13 '22 10:10

Stephen C


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.

like image 20
Brian Roach Avatar answered Oct 13 '22 09:10

Brian Roach