Sean Sean - 3 months ago 10
Java Question

Comparing file name to string

I have hit a road block in a program I am writing in Java. The program basically copies folders and files from multiple locations into one folder to make backing up code from multiple locations on my computer easier. The problem I have is that I don't want to copy specific folders, in this case "

workspace/.metadata
". The start of the code I am having issues with is below:

public void copyFolder(File in, File out, String loc)
throws IOException{

String check = in.getName().substring(1);
System.out.println("loc:"+loc+"check: "+check);
if(loc.equals("java")){
if(check.equals("metadata")){
System.out.println("failboat");
//statusBox.append("failboat");
}
}


And this is the result I see:

loc:java
check: orkspace2
loc:java
check: metadata
loc:java
check: lock


I've had other's look at the code and they agree it should work. I've even created a replica of the code in a test file:

String test = "fmetadata";
String loc = "java";
String check = test.substring(1);
if(loc.equals("java")){
if(check.equals("metadata")){
System.out.print("failboat");
}else{
System.out.println("WTF");
System.out.print(test+ ": :"+check);
}
}


And the result?

failboat


There is a dent in my desk the size of my forehead from trying to figure this out.

Answer

If that output you posted is the actual output:

loc:java
check: orkspace2
loc:java
check: metadata
loc:java
check: lock

It does not match the code you've pasted, as you do not print a newline between the two items:

System.out.println("loc:"+loc+"check: "+check);

If this is truly what you are seeing with that code then I would say the problem is that loc has a stray newline at the end, and is actually "java\n" rather than "java" as you expect. So you should go back and examine how you generate the value you pass through loc to begin with before calling that function.


If this is the case, some suggestions for diagnostics improvements that could help you notice these kinds of issues sooner (in addition to stepping through with a debugger):

// quote your strings to spot whitespace, print length to spot unexpected
// unprintable characters.
System.out.println("loc: \""+loc+"\" "+loc.length());
System.out.println("check: \""+check+"\" "+check.length());

And:

if(loc.equals("java")){
    // make sure you're getting to this point, don't assume that the first
    // if condition was satisfied:
    System.out.println("grumpycat"); // <----
    if(check.equals("metadata")){
        System.out.println("failboat");
    }
}