2017-03-04 5 views
-1

내 코드에 따르면 내가 선택한 파일을 주어진 디렉토리에 어떻게 저장할 수 있습니까? 여기 Uri가 캡처되었지만 오디오 파일을 특정 폴더에 저장할 수 없습니다. 어디에서 문제가 될 수 있습니까? outputStream을 쓰는 동안 내가 한 모든 실수는 무엇입니까?파일을 선택하고 안드로이드에 주어진 폴더에 저장해야합니다

public class Upload extends AppCompatActivity { 
    File folder; 

    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     setContentView(R.layout.splashscreen); 

     /* New Handler to start the Menu-Activity 
     * and close this Splash-Screen after some seconds.*/ 
     folder = new File(Environment.getExternalStorageDirectory() + "/Audios"); 
     File folder1 = new File(Environment.getExternalStorageDirectory() + "/"); 
     if (!folder.exists()) { 
      folder.mkdir(); 
     } 
     for (File f : folder.listFiles()) { 
      if (f.isFile()) { 
       String name = f.getName(); 
       // System.out.print(name); 
       Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show(); 
      } 
      // Do your stuff 
     } 
     Intent intent_upload = new Intent(); 
     intent_upload.setType("audio/*"); 
     intent_upload.setAction(Intent.ACTION_GET_CONTENT); 
     startActivityForResult(intent_upload, 1); 

    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

     if (requestCode == 1) { 

      if (resultCode == RESULT_OK) { 
       FileInputStream fileInputStream = null; 
       //the selected audio. 

       Uri uri = data.getData(); 
       Toast.makeText(getApplicationContext(), uri.getPath(), Toast.LENGTH_SHORT).show(); 
       File test = new File(uri.getPath()); 
       try { 
        fileInputStream = new FileInputStream(test); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } 
       try { 
        FileOutputStream outputStream = new FileOutputStream(folder, true); 
        int bufferSize = 1024; 
        byte[] buffer = new byte[bufferSize]; 
        int len = 0; 
        while ((len = fileInputStream.read(buffer)) != -1) { 
         outputStream.write(buffer, 0, len); 
        } 

       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
     super.onActivityResult(requestCode, resultCode, data); 
    } 

} 

답변

0

이 "파일을 선택"하지 않습니다. 사용자는 콘텐츠를 선택할 수 있습니다. 결과 코드 RESULT_OK 경우

onActivityResult()에서 상기 IntentUri는 콘텐츠의 선택된 부분을 가리키는 것이다. 해당 콘텐츠에 InputStream을 얻으려면 ContentResolveropenInputStream()을 사용하십시오. 거기에서 어떤 파일에 FileOutputStream을 연 다음 InputStream에서 OutputStream으로 바이트를 복사하는 등 필요한 작업을 수행하십시오.

BTW, ACTION_GET_CONTENT은 입력으로 Uri을 취하지 않습니다. setDataAndType()setType()으로 바꿉니다.

+0

내 질문을 편집했습니다. 여전히 파일을 저장할 수 없습니다. 해결책을 가져 주셔서 감사합니다. – HRCJ