如何使用SAF将音频文件复制到可移动SD卡

时间:2017-05-02 18:08:37

标签: android audio inputstream storage-access-framework

我想将音频文件复制到Android上的可移动SD卡上。我已阅读并尝试了存储访问框架(SAF)并能够成功编写文本。不幸的是,当我按照相同的方法写一个音频文件时说一个.mp3,它会创建一个空文件,也不会抛出异常。

我通过这种方式获取目标目录的路径:

Intent intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
startActivityForResult(intent, requestCode)

在onActivityResult中,这就是我尝试复制文件的方式:

protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
//Checking requestCode and reslutCode removed for brevity
Context context = this;
Uri treeUri = resultData.getData();
String newAudioFile = "newAudioFile.mp3";
DocumentFile pickedDir = DocumentFile.fromTreeUri(context, treeUri);
String extension = newAudioFile.substring(newAudioFile.lastIndexOf('.')+1,newAudioFile.length());
String srcFilePath = "/storage/emulated/0/Downloads/beat.mp3";

try {
  DocumentFile newFile = pickedDir.createFile("audio/"+extension, newAudioFile);
  OutputStream out = context.getContentResolver().openOutputStream(newFile.getUri());
  InputStream in = new FileInputStream(srcFilePath);
File srcFile = new File(srcFilePath);
  Log.d("srcFile " + srcFile.exists());// returns true
  Log.d("!srcFile.isDirectory() " + !srcFile.isDirectory());// returns true

  byte[] buffer = new byte[1024];//new byte[in.available()] gave same results
  int read;
//in.read(buffer) below returns -1
//from the docs that means "no byte is available because the stream is at the end of the file"
  while ((read = in.read(buffer)) != -1) {
    out.write(buffer, 0, read);
  }
  in.close();
  // write the output file (You have now copied the file)
  out.flush();
  out.close();
} catch (Exception e) {
  Log.d("Exception " + e);
}
}

当我使用它来获取byteArray时,长度为0因此不返回任何字节,即in.read(缓冲区)返回0

public byte[] inputStreamToByteArray(InputStream inStream) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inStream.read(buffer)) > 0) {
    baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
}

我在使用API​​ 22的真实设备上进行测试。应用程序的配置:

minSdkVersion 21 targetSdkVersion 25

我需要一些帮助,因为我现在已经没有选择了。感谢。

以下是问题示例项目的link

0 个答案:

没有答案