I am trying to make my file manager and have encountered such a problem. When I try to select a file, not a directory, my program crashes. You can tell how to make the program allow opening only directories. Specifically, I need to find out if there are any algorithms or methods for determining the file extension.

/*Класс который отвечает за работу файлового менеджера*/ public class FileManager extends AppCompatActivity implements AdapterView.OnItemClickListener { ListView listOfDirs; String [] paths = {"/storage/emulated/0/", "/storage/extSdCard/"}; String currentPath = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_file_manager); listOfDirs = (ListView) findViewById(R.id.list); listOfDirs.setOnItemClickListener(this); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, paths); listOfDirs.setAdapter(adapter); } @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { String localPath = paths[position];/*Здесь я определяю какую диру выбрал юзер и осуществляю переход в эту диру*/ transition(localPath);//Сам переход listOfDirs.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, paths)); /*Вывод на экран директорий, находящихся по заданному пути*/ } void transition(String currentDirectory){ if(currentPath.equals("")){ //Проверяет установлен ли первичный путь currentPath = currentDirectory; } else { currentPath = currentPath + currentDirectory; } File file = new File(currentPath); paths = file.list();//Парсинг директории и занесение всех ее элементов в массив } } 
  • Maybe you need to determine that a particular FS object is a directory? - Vladimir Martyanov
  • Or like this. Yes, most likely it will be more correct. - Nick
  • one
    File file = new File (path); boolean isDirectory = file.isDirectory (); - Vladimir Martyanov
  • Thanks, but still. Is it possible to somehow find out the file extension? - Nick

3 answers 3

The easiest way to look to the last point and cut everything before it.

For this there is a function lastIndexOf.

Function trimming extension:

 private static String getFileExtension(String mystr) { int index = mystr.indexOf('.'); return index == -1? null : mystr.substring(index); } 
     String path = "file.txt"; Pattern p = Pattern.compile("\\.\\w+$"); Matcher m = p.matcher(path); m.find(); String ext = m.group(); System.out.println(path + " " + ext); 
       Path path = Paths.get("foo/bar.java") if (path.endsWith(".java")){ //Do stuff }