R
R
rsdev2015-10-11 09:49:41
Java
rsdev, 2015-10-11 09:49:41

How to find all files of a given format on a real device?

Actually the question is in the title. I want to find all paths to JPG files on the device. I test the code on 4 devices, on 2 I get an error, on 1 everything works like clockwork, on 4 the error is permanent.
Looking for files like this:

public void findFile(File dir) throws IOException {

        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                NumberFor++;
                try {
                    if (file.isDirectory()) {
                        findFile(file);
                    }
                }
                catch (Exception e){
                    Toast.makeText(this,String.valueOf(e.getMessage()),Toast.LENGTH_SHORT).show();
                }

            }
            for (File file : files) {
                if (file.isFile()) {   //проверяем, файл ли это
                    String fileName = file.getName();
                    String ext = fileName.substring(fileName.lastIndexOf('.') + 1,
                            fileName.length());
                    if (ext.equalsIgnoreCase("JPG")) {
                        fileList.add(file.getAbsolutePath());
                    }
                }
            }
        }
    }

I am looking for all files at the address "/"
In the logs, it swears at nullpointerexception in the isDirectory () method. With manual debugging, more than 100 cycles pass (I didn’t measure further), it seems to find a folder that it cannot read.
How to overcome, tell me.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Danil Antoshkin, 2015-10-11
@TwerTrue

Take the code in a block, otherwise it’s not very good in one line

O
Oleg Gamega, 2015-10-11
@gadfi

if(file!=null&&file.isDirectory()){....

S
sivabur, 2015-10-11
@sivabur

in the line File[] files = dir.listFiles();
files can take the value null (if access to the folder is denied) and then the program generates an error, so after the specified line it is necessary, apparently, to insert a check for null: something like this: if (files == null){
files = new File []{};
}
Depends on the rights. If from under the root, the launch is done according to the idea, there should be no errors.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question