user2137130
user2137130

Reputation: 11

Why is File.separator using the wrong character?

I'm trying to add functionality to a large piece of code and am having a strange problem with File Separators. When reading a file in the following code works on my PC, but fails when on a Linux server. When on PC I pass this and it works:

fileName = "C:\\Test\\Test.txt";

But when on a server I pass this and get "File Not Found" because the BufferedReader/FileReader statement below swaps "/" for "\":

fileName = "/opt/Test/Test.txt";
System.out.println("fileName: "+fileName);
reader = new BufferedReader(new FileReader(new File(fileName)));

Produces this output when run on the LINUX server:

fileName: /opt/Test/Test.txt

File Not Found: java.io.FileNotFoundException: \opt\Test\Test.txt (The system cannot find the path specified)

When I create a simple Test.java file to try and replicate it behaves as expected, so something in the larger code source is causing the BufferedReader/FileReader line to behave as if it's on a PC, not a Linux box. Any ideas what that could be?

Upvotes: 1

Views: 724

Answers (1)

Josh
Josh

Reputation: 760

I don't see where you used File.separator. Try this instead of hard coding the path separators.

fileName = File.separator + "opt" + File.separator + "Test" + File.separator + "Test.txt";

Upvotes: 1

Related Questions