【发布时间】:2017-05-03 17:21:28
【问题描述】:
在一个 Android 项目中,我将音频文件读入 InputStream,然后将其写入设备上的另一个位置。读取时,sn -p 所示in.read(buffer) 返回-1。运行应用程序后,我使用手机的文件管理器应用程序找到要播放的文件。但它不会播放,因为文件是空的,即大小为0 bytes。使用InputStreams和OutputStreams读写音频文件的正确方法是什么?
try {
DocumentFile newFile = pickedDir.createFile("audio/mp3", "New File");
OutputStream out = getContentResolver().openOutputStream(newFile.getUri());
InputStream in = new FileInputStream("/storage/emulated/0/beat.mp3");
// To check whether the source file exists
File testFile = File("/storage/emulated/0/beat.mp3");
Log.d("App", "exists: " + testFile.exists() + " len: " + testFile.length());//exists: true len: 0
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
} catch (Exception e) {
Log.d("Exception ", e.getMessage());
}
【问题讨论】:
-
避免使用硬编码的文件系统路径。参考这个链接developer.android.com/about/versions/…
-
@nandsito 指出。但这仅用于演示目的。
-
您再次发布了相同的代码以及所有安全的内容。我建议你只发布代码来读取文件。专注于真正的问题。我也没有看到 file.exists() 和 file.length()。那应该在里面。没有安全。
-
所以你不应该从一开始就谈论复制文件。仅阅读。
-
@greenapps 我已经更新了,希望更好。
标签: java android audio inputstream outputstream