I want to read a file say c.txt
in java in windows. So can anybody suggest me that how can I format a system path to a file say D:\a\b\c.txt
to D:/a/b/c.txt
in java? I know it will work like this D:\\a\\b\\c.txt
but I want to use this D:/a/b/c.txt
. Thanks!
Asked
Active
Viewed 2,828 times
2

divine
- 33
- 1
- 2
- 8
4 Answers
3
I'm not sure of your problem but rarely is it good practice to hard code /
or \
. Use Java's File.separator
to help you.

Andrew Thompson
- 168,117
- 40
- 217
- 433

Josh England
- 182
- 9
1
String file="D:\\a\\b\\c.txt";
file=file.replace('\\','/');
System.out.println(file);
output D:/a/b/c.txt
But if you are trying to make it more platform dependent you should use File.separator
(for replacement based on Strings) or File.separatorChar
(for replacement based on chars).

Pshemo
- 122,468
- 25
- 185
- 269
1
You could use the char
replace: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace%28char,%20char%29
Example:
String pathToFile = "D:\\a\\b\\c.txt";
pathToFile = pathToFile.replace('\\','/'); <-- with ' and not "
Documentation of replace(char, char)
:
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

Francisco Spaeth
- 23,493
- 7
- 67
- 106