質問

Im trying that a program that watch the changes of a directory. The program must say:

  1. If the File was deleted
  2. If the File was modified
  3. If the File is new.

For that, im using two ArrayLists, in the first ArrayList (initiallist) i'm saving the content of a FilePath. Then I do a pause. The user can change something from the FilePath like insert new files, or delete other files or modify. When I press a key, I save in the second ArrayList again the content of the FilePath.

Then I compare the items and here is the problem. How can I compare it that?

I use that:

for(int i=0; i<initiallist.size(); i++){
        for(int j=0; j<finallist.size(); j++){
            int compname = initiallist.get(i).getName().compareTo(finallist.get(j).getName());
            //If name is the same
            if(compname==0){
                //If modify date and length is the same
                if(initiallist.get(i).getLength()==finallist.get(i).getLength() && initiallist.get(i).getDate()==finallist.get(i).getDate()){
                    System.out.println("The file: "+initiallist.get(i).getName()+ " --> wasn't modified." );
                    break;
                }else{
                    System.out.println("The file: "+initiallist.get(i).getName()+ " --> was modified." );
                }
            }else if(compname!=0){

            }else{

            }
        }
    }

I need some help for take the new Files and the Deleted Files. THANKS! :)

役に立ちましたか?

解決 2

To compare objects in java use .equals() method instead of "==" operator

Change

initiallist.get(i).getDate()==finallist.get(i).getDate()

to

initiallist.get(i).getDate().equals(finallist.get(i).getDate())

他のヒント

The == comparison is one which only works on primitive types. In order to compare objects, such as a Date object, you must use equals() or compareTo()

== compares the ADDRESS of the two objects, not the actual VALUES of the objects.

if(date1.equals(date2))
    //do something

OR

if(date1.compareTo(date2) == 0)
    //do something

If you are using Java 7, you can also use in built support for monitoring the file system

Monitor File System with WatchService

It will save you a lot of extra work.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top