File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes filename conversion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "filename conversion" Watch "filename conversion" New topic

filename conversion

Maarten Vergouwen
Ranch Hand

Joined: Jan 12, 2004
Posts: 60
hi all,
I've a small problem.
I want to retrieve a filename from the user, and then pass it to a FileInputStream object. The problem is that the user will ofcourse type in the file name as being 'c:\dirA\dirAA\file.ext' or something similar, whilst the object expects double '\\' as seperators:
new FileInputStream("c:\\dirA\\dirAA\\file.ext");
Now I can ofcourse write a loop to go through the code and change every single '\' into a double '\\', but I cant help feeling there must be an easier way.... anyone want to offer an idea?
[ February 05, 2004: Message edited by: Maarten Vergouwen ]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

The constructor does not want double backslashes in the argument. It's just that to embed a single backslash in a Java string literal, you have to write a double one. The actual string represented in this Java code
new FileInputStream("c:\\dirA\\dirAA\\file.ext")
only contains the characters
You can check this, if you don't believe me, by running
and you'll find that the printed number corresponds to the length of the string with the single backslashes.
In any event, the problem you're imagining isn't a problem. Use the user's input as-is, and it will work just fine.

[Jess in Action][AskingGoodQuestions]
Nischal Topno
Ranch Hand

Joined: Nov 24, 2001
Posts: 45
As Ern said there is no need to escape the "\" character. The constructor does not need to escape the "\" character.
The following code will help you:

Even if the user enters c:\dirA\dirAA\file.ext (without two "\") in the console, the code is going to read the data from the file "file.ext"
[ February 06, 2004: Message edited by: Nischal Topno ]
Maarten Vergouwen
Ranch Hand

Joined: Jan 12, 2004
Posts: 60
Thank you
Billybob Marshall
Ranch Hand

Joined: Jan 27, 2004
Posts: 202
Just use forward slashes, regardless of the platform.
I agree. Here's the link:
subject: filename conversion
It's not a secret anymore!