Home > Blockchain >  Two strings appear to be equal, but they are not
Two strings appear to be equal, but they are not

Time:10-18

I want to open a file using the argument I get via a socket. When I extract the filename using split(), the the file does not open. But when I hardcode the value it does open. What am I missing here? I would expect the strings to be equal.

String name = str.split(";")[2];

System.out.println("Filename: "   name);

String path1 = new String("Input_Blatt3/Sample.txt");
String path2 = new String("Input_Blatt3/"   name);

System.out.println("Path1: "   path1);
System.out.println("Path2: "   path2);

System.out.println("path1.equals(path2) = "   path1.equals(path2));

Output:

Path1: Input_Blatt3/Sample.txt
Path2: Input_Blatt3/Sample.txt
path1.equals(path2) = false

CodePudding user response:

There could be unprintable characters hidden in the String. Use getBytes to get all the characters of a String and print those. You'll probably find something you didn't expect.

Alternatively you could also replace everything that isn't a printable character with nothing.

CodePudding user response:

There could be some trailing white spaces, which you would not see at the console output.

You can try name.strip() (or trim() if your JDK version is lower 11) to ensure that there's nothing but the file name in the string.

  • Related