• 0

[Java] My code makes folders instead of files... sometimes


Question

Hi all,

I basically have some code that will take a file, copy it's contents to another file, and delete the original. However, sometimes this makes the file name as a folder instead of a file. For example, it may make c:\file.txt as a FOLDER, not a text file. My code is below, which does sometimes work but like I said, it sometimes makes a folder instead. Does anyone have any ideas why?

	   File originalLogFile = new File(userDir + "/migration.log");
	   File renamedLogFile = new File(migrationLogFolder + "/" + runName + "/" + testFileName + ".txt");

		trace("Trying to create file: " + renamedLogFile.getPath());

		// If the folder doesn't exist, make it.
		if(!renamedLogFile.exists()) {
			renamedLogFile.mkdirs();
		}

		// Move and rename from migration.log to the above.
		if(originalLogFile.exists()) {
			if(renamedLogFile.exists()){
				renamedLogFile.delete();
			}
			originalLogFile.renameTo(renamedLogFile);
		}

Any help is much appreciated.

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

Maybe I'm being stupid, but it seems extremely obvious:

		if(!renamedLogFile.exists()) {
			renamedLogFile.mkdirs();
		}

Here if "renamedLogFile" doesn't exist, you call mkdir() on it, which creates a directory named after the file. If what you want to do is create the file, you should call createNewFile(). http://java.sun.com/j2se/1.4.2/docs/api/ja...createNewFile()

Link to comment
Share on other sites

  • 0

Thanks for the reply. I thought mkdirs() only made parent folders, not the file itself?

Would createNewFile() make any necessary parent folders?

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.