Compare a file with an Argument

1

I have the following program:

File[] ficheros2=new File(".").listFiles(new FileFilter() { 
public boolean accept(File fichero) {
return fichero.isFile();
}
});
int ocultos2=0;
int totalFicheros=0;
for(File fichero :ficheros2) {
//System.out.println(fichero.getName()); //Si queremos mostrar todas las carpetas 

// OCULTOS
if (fichero.isHidden()  ){ 
   System.out.println("L'arxiu es ocult." +args[0]);
   ocultos2++;
}  
if (!fichero.isHidden() ) { 
    System.out.println("L'arxiu es lliure"+args[0]);
  totalFicheros ++;   
}}

System.out.println("Numero de ficheros visibles "+totalFicheros);
System.out.println("Número de ficheros ocults :"+ocultos2);      

I have no idea how to compare the files with argumento[0] .

That is to say      if (!fichero.isHidden() ) {

It should be something like this:

if(!fichero.isHidden() && fichero.equals(args[0]) .

I have tried with equals, ==, and a thousand other things ... but there is nothing that works for me .. Can you tell me what I can compare them with?

The idea of the program in summary mode is:

El Filtro me saca solo los archivos. 

Si el fichero es oculto y es igual que el argumento 
......

Si el fichero es visible y es igual que el argumento
.....

thanks!

    
asked by Montse Mkd 28.02.2017 в 20:02
source

1 answer

1

You can not directly compare a File with a String (args) and expect to receive a result that is useful for something:  - File is a descriptor for a file or a folder.  - String is a string of characters

The comparison == in Java checks if the reference of the variable points to the same object, that can not be in the case of objects of type File and String because they are of completely different classes. For String :

    String foo = "foo";
    String bar = "bar";
    String foobar = foo;
    String barfoo = new String(foo);
    System.out.println(String.format("foo con foo    %s - %b", bar, foo == bar));
    System.out.println(String.format("foo con foobar %s - %b", foobar, foo == foobar));
    System.out.println(String.format("foo con barfoo %s - %b", barfoo, foo == barfoo));
    System.out.println(String.format("foo con \"foo\"  %s - %b", foo, foo == "foo"));

results in:

foo con foo    bar - false // <- lo esperado
foo con foobar foo - true  // <- igual, porque apuntan al mismo objeto
foo con barfoo foo - false // <- las cadenas son igual, pero el objeto no lo es
foo con "foo"  foo - true  // <- eso queda true, porque "foo" y "foo" apuntan al mismo String

The comparison with .equals() checks if the content (according to definition) is equivalent between the two objects. To begin with in the specific case, two objects can not be equal if one is of type File and the other of type String .

If you want to compare something, you should compare for example file.getAbsoluteFile() with String passed as argument.

    
answered by 28.02.2017 / 20:14
source