2015-01-10 5 views
4

Android 앱을 만들고 디렉토리에 파일을 나열하고 싶습니다. 그때디렉토리에서 호출 될 때 File.listFiles가 null을 반환 할 수있는 이유는 무엇입니까?

int length = files.length; 
를 호출하여 files 배열의 길이를 얻을 때

File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); 

를 호출하여 만든 File 목적은, 내가

File[] files = path.listFiles(new CustomFileFilter()); 

path를 호출하여이 작업을 수행 할 것입니다

files이 null이기 때문에이 줄은 NullPointerException이됩니다.

내가 확인 한 나는

System.out.println("Path exists: " + path.exists()); 

를 호출에 존재하는 파일을 나열하려고 내가 응용 프로그램을 실행할 때, 그것은 안드로이드 스튜디오 콘솔에서

Path exists: true 

를 인쇄 path 경우, 그래서 디렉토리가 존재합니다.

또한

/storage/emulated/0/Download 

는 그래서 path 디렉토리, 그리고 파일입니다 경로 이름을 인쇄했습니다.

path은 (는) 디렉토리이므로 NullPointerException을 얻는 이유에 대해 잘 모릅니다.

편집는 다음 CustomFileFilter 클래스는 다음과 같습니다

public class CustomFileFilter implements FileFilter { 

    // Determine if the file should be accepted 
    @Override 
    public boolean accept(File file) { 
     // If the file isn't a directory 
     if(file.isDirectory()) { 
      // Accept it 
      return true; 
     } else if(file.getName().endsWith("txt")) { 
      // Accept it 
      return true; 
     } 
     // Don't accept it 
     return false; 
    } 
} 
+0

아마도 'CustomFileFilter' 클래스로 인해 Array에 파일이 없습니다. 'path.listFiles()'메소드로 같은 코드를 시도해보십시오. –

+0

오, 질문에'CustomFileFilter' 클래스를 추가하는 것을 잊지 마십시오. –

+2

'path.isDirectory()'와'path.canRead()'의 결과를 보여줍니다. 파일이라고 말하는 것만으로 파일이되지는 않습니다. – chrylis

답변

6

는 AndroidManifest.xml에이 추가 :

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

이 권한

당신이 파일을 읽을 수 있습니다; 이 사용 권한을 사용하지 않으면 listFiles()list()은 모두 NullPointerException을 반환합니다. 당신이 코드에 의해 권한을 부여해야합니다 안드로이드 SDK> (23)에서 작업하는 사람들을 위해

String dir = "/storage/emulated/0/Download/"; 
     File f = new File(dir); 
     String[] files = f.list(); 
     for(int i=0; i<files.length; i++){ 
      Log.d("tag", files[i]); 
     } 
+0

확실하지 않지만 파일에 액세스해서는 안되기 때문에 사용자에게 읽기 권한이없는 경우 NullpointerException 대신 IOException이 발생합니까? – Sashwat

+0

고마워요! 이것은 효과가있다! –

+0

@Sashwat이 권한을 제거하여 NullpointerException이 throw됩니다. –

2

:

: 같은 사용 무언가를

그리고 여기가 /storage/emulated/0/Download에있는 모든 파일을 보여주는 예입니다

boolean grantedAll = ContextCompat.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; 
if (!grantedAll) 
    { 
    ActivityCompat.requestPermissions(thisActivity, 
      new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 
      REQUEST_PERMISSIONS); 
    }