-1

I'm trying to write a file path or URL to a text file.

String myString = "http://example.com:96";
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(myString.getBytes());

I wonder why the back slash is written to the file even though we don't need an escape char for a forward slash??

http:\/\/example.com:96 

(note that if I read back the URL string to a java program and print to the console, I don't see the back slash anymore. http://example.com:96 )

Is there a way to omit the back slash character?

  • If you defined `myString` as `http:\/\/example.com:96`, you don't need to escape forward-slashes - `String myString = "http://example.com:96";` will work just fine – Will Warren Jul 24 '14 at 14:23
  • Are you going to be reading the file back into your Java program or is it going to be used elsewhere? – Xinzz Jul 24 '14 at 14:23
  • @Xinzz What does it matter? – Dave Newton Jul 24 '14 at 14:24
  • Just wondering if he's trying to read/write to a properties file. – Xinzz Jul 24 '14 at 14:26
  • I just edited the question. myString = "http://example.com:96" and I just want to write the ULR/filepath the way we normally see them so it won't be OS/language specific. Thanks. – Dustin Wind Jul 24 '14 at 14:57

1 Answers1

0

You're going to write exactly (in byte terms) what's in your string. So the backslashes will already be there. The stream won't be escaping them for you.

Note also, I would investigate Writers for writing strings, and watch your character encoding! The above is using your default character encoding to determine the bytes to write to your file, and running this in a different environment may yield different results!

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440