在Android項目中,我正在將音頻文件讀取到InputStream
中,並將其寫入設備的其他位置。閱讀時,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());
}
避免使用硬編碼的文件系統路徑。請參閱此鏈接https://developer.android.com/about/versions/android-4.2.html#MultipleUsers – nandsito
@nandsito注意。但是,這僅用於演示目的。 – Godfred
您再次發佈相同的代碼與所有安全的東西。我建議你只發布代碼來閱讀文件。專注於真正的問題。我也沒有看到file.exists()和file.length()。這應該是在它。沒有安全。 – greenapps