Can't delete a file using threads

2019-08-18 07:35发布

I used the following codes but i am unable to delete the file. Can anyone help?

public class Delete{

    public static void main(final String[] args){
        final Thread a = new Thread();
        a.start();
    }

    public void run(){
        final String fileName = "default\\sample.txt";

        // A File object to represent the filename

        final File f = new File(fileName);

        // Make sure the file or directory exists and isn't write protected

        if(!f.exists()){
            throw new IllegalArgumentException(

            "Delete: no such file or directory: " + fileName);
        }

        if(!f.canWrite()){
            throw new IllegalArgumentException("Delete: write protected: "

            + fileName);
        }

        // If it is a directory, make sure it is empty

        if(f.isDirectory()){

            final String[] files = f.list();

            if(files.length > 0){
                throw new IllegalArgumentException(

                "Delete: directory not empty: " + fileName);
            }

        }

        // Attempt to delete it

        f.delete();

    }

}

Or is there any other way to delete a file using threads?

3条回答
一夜七次
2楼-- · 2019-08-18 07:57

You have to start your thread with:

Thread a = new Thread(new Delete());
a.start();

Update:

Your Delete class also needs to implement Runnable.

查看更多
Viruses.
3楼-- · 2019-08-18 08:01

The method run() is not called

import java.io.File;

public class Delete extends Thread {

    public static void main(String[] args) {

        Delete a = new Delete();
        a.start();
    }

    public void run()
    {
        String fileName = "C:\\temp\\todelete.txt";
        File f = new File(fileName);
        if (!f.exists())
            throw new IllegalArgumentException("Delete: no such file or directory: " + fileName);
        if (!f.canWrite())
            throw new IllegalArgumentException("Delete: write protected: " + fileName);
        if (f.isDirectory()) {
            String[] files = f.list();
            if (files.length > 0)
                throw new IllegalArgumentException("Delete: directory not empty: " + fileName);
        }

        boolean success = f.delete();

        if (!success)
            throw new IllegalArgumentException("Delete: deletion failed");

    }

}
查看更多
成全新的幸福
4楼-- · 2019-08-18 08:18

This is what you are looking for.

public class Delete extends Thread {

    public static void main(String[] args) {

        Thread a = new Delete();

        a.start();

    }

    public void run() {
        // your implementation
    }
}
查看更多
登录 后发表回答