Question

This question looks like very similar to: Concatenating null strings in Java

But my issue is some different.

I want to build an absolute path to a file:

String path = properties.get("path"); // returns /home/myuser/relativepath/ , ends with bar /
String file = currentFile; // currentFile values "file.txt"
String result = path + file; // this results in /home/myuser/relativepath/nullfile.txt

Why is there than 'null' text? That's the reason my application does not work now.

I have review it in Windows and Linux. In Windows it works perfectly. In Linux, I have this issue.

I uploaded properties file and then, edited with vi command. Maybe is this the problem? Shouldn't I use this way to generate an absolute path, and use File.Separator property in Java?

EDIT: I have post my final right answer with detailed steps. I hope it would be useful.

Was it helpful?

Solution 2

Well, the complete and detailed steps to fix my issue are these (maybe any of them could not be necessary, but I prefer to write them all):

  1. Create config file in Linux with vi, emacs, ... (not upload file from Windows).
  2. Edit file with vi, emacs... At the end of each path, do not include directory separator character ( / ).
  3. Check variables before contatenate them. Make sure they don't have any space and other unexpected character.
  4. Concatenate variables with:

    String result = path + File.separator + file;

I hope this would be useful. Thank you all for your suggestions. Regards

OTHER TIPS

My bet (though I have not seen Java behave this way) is there's a null-ish character (such as a carriage return) of some sort in your properties file which Windows handles at the OS level so Java/Properties doesn't see it.

As a first pass, try printing the length and last few characters of your path string, e.g.:

for(int i = Math.max(0, path.length()-5); i < path.length(); i++) {
  System.out.print(path.charAt(i)+":"+((int)path.charAt(i))+" ");
}
System.out.println(path.length());

Willing to bet the last character, on Linux, is not what you'd expect. The right fix would then be to clean up your properties file so that it's compatible on both OSes.

What do you expect?
Yo´re doing a String result = path + result;
int a = 1 + a would be similar... don´t use a variable to init itself.
(That can´t be your code in the first place, if you´re getting this output.)

result is path+file :

    String path = properties.get("path");
    String file = currentFile; 
    String result = path + file; 
                            ^ 
                       change here

the result is: /home/myuser/relativepath/file.txt

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top