[英]Android File not created on SD card
我正在嘗試在設備上的SD上創建一個文件。 這工作一周前,但現在不是,我不明白為什么。
Logcat打印:
java.io.FileNotFoundException ...pathtofile... (no such file or directory)
因此,該文件尚未創建。 我對android清單有正確的權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
我這樣創建文件:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
base = Environment.getExternalStorageDirectory().getAbsolutePath();
}
String fname = File.separator +"VID_"+ timeStamp + ".3gp";
mediaFile = new File(base+fname);
然后我檢查它是否存在:
if(mediaFile.exists()){
Log.v("mediaFile","ex");
}else{
Log.v("mediaFile","no ex");
}
日志說它不存在。 我也嘗試過file.createNewFile(),但它不起作用。
所以,一周前它正在工作,現在它不起作用,它可能是SD卡的問題???? 可能是某種類型的BUG !!! ????
謝謝
編輯:更多代碼
創建文件的功能是:
private static File getOutputMediaFile()
來自:
private static Uri getOutputMediaFileUri(){
return Uri.fromFile(getOutputMediaFile());
}
並設置為mediarecorder輸出為:
vMediaRecorder.setOutputFile(getOutputMediaFileUri().toString());
所以,當我做mediarecorder.prepare()時:
try {
vMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.v("RELEASE VIDREC1",e.toString());
releaseMediaRecorder();
return false;
} **catch (IOException e) {
Log.v("RELEASE VIDREC2",e.toString());
releaseMediaRecorder();
return false;**
}
粗體捕獲是運行的,並打印:
java.io.FileNotFoundException ...pathtofile... (no such file or directory)
您只需創建對象mediaFile,而不是實際文件。 用這個:
if(!f.exists()){
f.createNewFile();
}
我試過這個,對我來說它有效。
final String filename = "file.3gp";
final String path = Environment.getExternalStorageDirectory() + "/" + filename;
File outputfile = new File(path);
if (!outputfile.exists()) {
try {
outputfile.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
}
MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(outputfile.toString());
try {
recorder.prepare();
recorder.start();
/*recorder.stop();
recorder.reset();
recorder.release();*/
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
試着看看它是否有效。 如果沒有,你可以添加getOutputMediaFile()的完整代碼嗎?
試試吧
String fname = "VID_"+ timeStamp + ".3gp";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
mediaFile = new File(android.os.Environment.getExternalStorageDirectory(),fname);
if(!mediaFile.exists())
{
mediaFile.createNewFile();
}
}
if(mediaFile.exists()){
Log.v("mediaFile","ex");
}else{
Log.v("mediaFile","no ex");
}
我的回答在這里 :
首先打開路徑,然后添加文件:
String dir = Environment.getExternalStorageDirectory(); // getAbsolutePath is not requried
File path = new File(dir);
File root = new File(path, "VID_"+ timeStamp + ".3gp";);
感謝您的幫助,我使用舊代碼解決了問題。 這很奇怪,因為“文件保存”部分沒有修改。 謝謝所有人,有點兒。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.