2

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!

divine
  • 33
  • 1
  • 2
  • 8

4 Answers4

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
1

You can use File API

File f = new File("c.txt");
System.out.println(f.getAbsolutePath());
System.out.println(f.getCanonicalPath());

or just simply substring

String fname = "D:\\a\\b\\c.txt".replace('\\', '/');
System.out.println(fname);
Alberto
  • 1,569
  • 1
  • 22
  • 41