根据我的代码,我之后可以选择一个文件,如何在选定目录中保存所选文件? 在这里我捕获了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 :(得分:0)
这不是"选择文件"。它允许用户选择一段内容。
在onActivityResult()
中,如果结果代码为RESULT_OK
,则Intent
会有Uri
指向所选内容。使用ContentResolver
和openInputStream()
获取该内容的InputStream
。从那里,执行您需要执行的操作,例如打开FileOutputStream
到某个文件,然后将字节从InputStream
复制到OutputStream
。
BTW,ACTION_GET_CONTENT
不会将Uri
作为输入。将setDataAndType()
替换为setType()
。