0

I am trying to get the absolute path of working directory, and pass it to a method. I am getting the path in the form

C:\eclipse\workspace\file.txt

but eclipse must receive it in the form:

C:\\eclipse\\workspace\\file.txt

So I am doing a replace, but it works only for one char, how to modify it?

String path = new File("").getAbsolutePath();
path  = path.replace( '\\', '\\\\' );
something  = method.read(path+"\\file.txt");
1
  • you only need to use double slashes when you have a string literal in your code. String path = new File("").getAbsolutePath(); will return a perfectly correct path. You shouldn't need to modify it. Commented Apr 6, 2011 at 3:20

7 Answers 7

3

Change this:

path  = path.replace( '\\', '\\\\' );

To this:

path  = path.replaceAll( "\\", "\\\\" );
Sign up to request clarification or add additional context in comments.

2 Comments

it keeps saying not valid constant of type char
Yes, but they were not present in the initial answer.
0

try using the replaceAll method.

Comments

0

Just use double quotes to represent more than one char. It's then called a String.

path = path.replace("\\", "\\\\");

Note that this requires a minimum of Java 1.5 to work.

See also:

Comments

0

You should use:

public String replaceAll(String regex,
                     String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement.

Comments

0

If you just want the current working directory, the simplest approach is this:

String currentdir = System.getProperty("user.dir");

2 Comments

and to pass the path to method?
Yep. It's just a bit more straightforward, standard than "new File("").getAbsolutePath();", in my personal opinion.
0

you can use
path = path.replaceAll( '\\', '/' ); it works

Comments

0

Not sure if this will help.. I ran into the same issue with the application I am building.

In my app, I basically use JFileChooser to graphically select the file I want. Long story short, the absolute path of the selected file comes back as "C:\Documents and Settings....\xCBL.xml"

The path was then passed to another class for manipulation, however it failed because of the single '\'. The fix -

String absPath = file.getAbsolutePath();
System.out.println("File Path:"+absPath);
String filePath = absPath.replaceAll("\\\\", "\\\\\\\\");
System.out.println("New File Path:"+filePath);

Output:

File Path:C:\Documents and Settings\tanzim.hasan\workspace\XML to Java\xcbl.XML
New File Path:C:\\Documents and Settings\\tanzim.hasan\\workspace\\XML to Java\\xcbl.XML

Hope the above helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.