我想開發一個程序,在特定的目錄(.txt文件)中創建一個文件並在其中存儲一些數據(例如字符串)。我也希望文件可以被用戶訪問(如果我去文件資源管理器,我可以查看我創建的文件,也可以用另一個程序或其他東西編輯它)。如何在Android中的特定目錄中創建.txt文件?
我試過很多東西,但是我無法管理這個工作。
這裏是我使用ATM代碼:
public void createFile(View view) throws IOException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt";
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Sonda Drive Test";
File mypath = new File(filepath);
if(!mypath.exists()) {
mypath.mkdir();
}
//now the mkdir returns true isntead of false
File myfile = new File(mypath, fileName);
try{
if(!myfile.exists()){
txtDebug.setText("Não existe ficheiro!");
myfile.createNewFile();
}
else{
txtDebug.setText("Já existe ficheiro!");
}
}catch (Exception e){
txtDebug.setText("Erro!");
}
}
我還添加權限波紋管:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
的問題是,當我做
myfile.createNewFile();
應用程序停止並關閉..但如果我評論該行,它也不會創建任何文件...
我在做什麼錯?
編輯:我管理使這個工作的API 22.我怎麼能做到API 25?
'程序Crashes'究竟你是什麼意思?你有什麼異常/堆棧跟蹤?請[編輯] int LogCat的詳細日誌輸出。由於缺乏背景而投票結束。 –
'mypath.mkdir();'。檢查返回值,因爲它可能無法創建目錄。如果它返回false,則向用戶顯示敬酒,並返回。 – greenapps
您可能會因爲「myfile」不存在而需要檢查該文件是否存在if(!myfile.exists()) –