views:

70

answers:

3

I am trying to refer to a location on my computer, however Java is telling me that I have the wrong syntax.

Is this line correct?

File newlyUploadedFile = new File("D:\\" + fileName);

The thing is the file gets uploaded correctly to the location I want it to go to, but I get the error:

java.io.IOException: The filename, directory name, or volume label syntax is incorrect

+6  A: 

Escape your backslashes in java strings, always.

File newlyUploadedFile = new File("D:\\" + fileName);

The IOException is caused by the system not finding the file you specified in filename. Try adding

newlyUploadedFile.exists();

and see what it returns. If your path returns false then you have a mistake in filename.

futureelite7
I don't think this is the problem. A missing escape in a String literal would result in a Java compilation error not an IOException.
Stephen C
yes I noticed that too. However, missing a slash will definitely cause problems with the path.
futureelite7
@futureelite7 - you are making assumptions. We don't know what `fileName` actually contains. What if it (already) starts with a `\\`?
Stephen C
The filename doesn't start with \
Ankur
In my experiences if windows sees multiple slashes then it gets ignored anyway. But I was addressing the fact that the poster initially forgot to escape his slashes.
futureelite7
+3  A: 

First off, the code as presented in the question will not compile. But since you have seen an IOException, you are clearly running different code.

In order to get an IOException complaining about pathname syntax, there must actually be something wrong with pathname. What does "D:\\" + fileName actually give you? Add a call to System.err.println(...) to see what it is.

Stephen C
Thanks I'll try that ... but why won't it compile - I tried to be brief and not give all the code. But I don't see why the bit I've given won't compile.
Ankur
@Ankur - now that you have fixed the text of the question it will compile :-)
Stephen C
+1  A: 

Notes:

  1. That exception text is coming from the Windows operating system, not from Java.

  2. There is never any need to use backslashes in Java filenames. At least if there is I've never encountered one in 13 years.

EJP
I'd love to know why the downvote. There are zero factual errors here.
EJP
Contra-voted that. It's indeed completely valid. The error is coming from the underlying filesystem and forward slashes have always worked as good in Windows.
BalusC