[英]Can't create file in the internal storage
我正在嘗試在內部存儲中創建一個文件,我按照 android 開發人員網站中的步驟操作,但是當我運行以下代碼時,沒有創建文件
請讓我知道我在代碼中缺少什么
代碼:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
默認情況下,這些文件是私有的,只有您的應用程序可以訪問並在用戶刪除您的應用程序時被刪除
用於保存文件:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
對於加載文件:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
嘗試獲取已安裝應用程序后存儲文件的路徑。以下代碼段將提供應用程序文件夾位置並添加所需的權限。
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
如果您正在處理不適合其他應用程序使用的文件,您應該通過調用getExternalFilesDir()
使用外部存儲上的私有存儲目錄。 此方法還采用類型參數來指定子目錄的類型(例如 DIRECTORY_MOVIES)。 如果您不需要特定的媒體目錄,請傳遞 null 以接收應用程序私有目錄的根目錄。
也許,這將是最佳實踐。
使用此方法創建文件夾
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
在此方法中,您必須將數據字符串作為第一個參數傳遞,並將要創建的文件名作為第二個參數傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.