Answer the question
In order to leave comments, you need to log in
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());
}
}
}
}
}
Answer the question
In order to leave comments, you need to log in
Take the code in a block, otherwise it’s not very good in one line
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 questionAsk a Question
731 491 924 answers to any question