該賞金到期的明天。此問題的答案有資格獲得 50聲望獎勵。 SebasSBM想引起更多人對這個問題的關注:
這只是寫一個TXT檔案,來吧!......為什么,谷歌,你為什么讓Android SDK如此難以使用?T_T
我希望我的應用程式生成的 TXT 檔案(以及包含它們的檔案夾)可以通過我手機的檔案瀏覽器訪問,甚至當我通過 USB 插入手機時可以從 PC 訪問。Android 的官方檔案描述了不同型別的存盤,具體取決于它是“內部”還是“外部”(Google 的術語)。當然,我不希望卸載應用程式時洗掉那些 TXT 檔案。
為避免任何混淆:
我想對應用程式中的檔案位置進行硬編碼這一事實并不意味著我必須使用完整的絕對檔案路徑作為引數。我的意思是相對檔案路徑將被硬編碼(相同的任務,相同的檔案,相同的位置)。
……那說……
該應用程式供個人使用(我的意思是自己使用),因此滿足 Google Play 商店的要求目前不是優先事項。
代碼示例(我嘗試過的)
try {
// Dedicated folder would be better...
// ...but not even in the root folder works...
// FIXME T_T
FileWriter writer = new FileWriter("/storage/emulated/0/myfile.txt");
writer.write(my_string_for_file);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
// ...always throws FileNotFoundException with Permission DENIED
這將是 PC 上的 Python,5 分鐘內完成!3個小時,我還是想不通??我想哭...
所以,我想總是在同一個檔案中保存一些輸出,在同一個路徑中。我希望當我通過 USB 插入我的 PC 以及從我手機的檔案瀏覽器時,可以從我的 PC 訪問該 TXT 檔案。例如,在 Python 中,對于 PC 應用程式,我會用 3 行代碼來實作這一點!在 Android 中不會更難,對吧?(或者我希望如此)
I am aware that, for what I describe here, it is technically "documents and other kind of files", and what Google or Android Developers consider "external storage" (but what Android Users consider Internal Storage!). Well, Android Developers Documentation has a section for this in this link.
But the example's Code Snippet is overkill for my needs: I don't want the User to choose filepath: I want to hardcode the TXT files' paths into /storage/emulated/0/myapp/ directory. Instead, the example seems to provide some way to open some kind of "Save As" file dialog, which I don't want.
According to this article, it suggests me to use Environment.getExternalStoragePublicDirectory, and if I look to this method's documentation it says this method is deprecated from API 28. I have been looking other docs about the subject, but I am still confused about how to proceed. Supposing that I already have the text I want to write into a String variable:
How would I make sure that files would be written to some dedicated folder like
/storage/emulated/0/myappor/storage/emulated/0/myfolderinstead of the root folder/storage/emulated/0? WillgetExternalFilesDir()return/storage/emulated/0or is there a better method?Which is the simplest code to just write the file containing the
Stringvariable's text with a hardcoded filename into the dedicated directory, but it will still persist after desinstalling the app?
If it is either /storage/emulated/0 or /storage/emulated/0/Documents, any of both is fine by me. The most important thing is that I can access those files from outside my App that is gonna make them and, if possible, that uninstalling the mentioned App won't delete them.
uj5u.com熱心網友回復:
Context.getExternalFilesDir(null)是新的替代方案,Environment.getExternalStoragePublicDirectory()但正如您所提到的,這將回傳一個目錄,一旦您卸載該應用程式,該目錄就會被洗掉。對于您需要使用的用例MediaStore,我完全同意您的看法:這變得非常復雜(我認為 android 這樣做是為了加強安全性,以便其他應用程式可以更輕松地瀏覽您放置在共享目錄中的檔案)。以下是使用 Media Store 執行所需操作的一些方法:
private void saveTxtFile(String fileName, String fileContent, Context context) throws IOException {
OutputStream fos;
try{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName); //file name
values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain"); //file extension, will automatically add to file
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS "/yourFolder/"); //end "/" is not mandatory
Uri uri = context.getContentResolver().insert(MediaStore.Files.getContentUri("external"), values); //important!
fos = context.getContentResolver().openOutputStream(uri);
} else {
String docsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
File file = new File(docsDir, fileName);
fos=new FileOutputStream(file);
}
try {
fos.write(fileContent.getBytes());
} finally {
fos.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
您還需要以下方法才能確定檔案是否已存在。我做了它所以它回傳一個 Uri 但你應該改變它以滿足你的需要
private Uri isFilePresent(String fileName, Context context) {
Uri contentUri = MediaStore.Files.getContentUri("external");
String selection = MediaStore.MediaColumns.RELATIVE_PATH "=?";
String[] selectionArgs = new String[]{Environment.DIRECTORY_DOCUMENTS "/yourFolder/"};
Cursor cursor = context.getContentResolver().query(contentUri, null, selection, selectionArgs, null);
Uri uri = null;
if (cursor.getCount() == 0) {
Toast.makeText(context, "No file found in " Environment.DIRECTORY_DOCUMENTS "yourFolder", Toast.LENGTH_LONG).show();
} else {
while (cursor.moveToNext()) {
String file = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME));
if (fileName.equals(fileName)) {
long id = cursor.getLong(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
uri = ContentUris.withAppendedId(contentUri, id);
break;
}
}
}
return uri;
}
請不要忘記將相應的權限添加到清單中以使其作業:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
順便說一句,這個答案做了類似的事情
uj5u.com熱心網友回復:
試試這個代碼,它將資料保存到檔案中,但保存在內部存盤中。更方便,因為現在很多設備沒有外卡。您至少可以使用 android 模擬器工具提取該檔案并將其保存到您的 PC:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class FileManager {
public static void writeToFile(String fileName, String data, Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(fileName, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
} catch (FileNotFoundException e) {
LLog.e(e, "File not found");
} catch (IOException e) {
LLog.e(e, "File write failed");
}
}
public static void addToFile(String fileName, String data, Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(fileName, Context.MODE_APPEND));
outputStreamWriter.append(data);
outputStreamWriter.close();
} catch (FileNotFoundException e) {
LLog.e(e, "File not found");
} catch (IOException e) {
LLog.e(e, "File write failed");
}
}
public static String readFromFile(String fileName, Context context) {
String resultStr = "";
try {
InputStream inputStream = context.openFileInput(fileName);
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();
bufferedReader.close();
resultStr = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
LLog.e(e, "File not found");
} catch (IOException e) {
LLog.e(e, "File write failed");
}
return resultStr;
}
public static String readFromFileInRawFolder(String fileName, Context context) {
String resultStr = "";
try {
InputStream inputStream = context.getResources().openRawResource(
context.getResources().getIdentifier(fileName, "raw", context.getPackageName()));
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();
bufferedReader.close();
resultStr = stringBuilder.toString();
} catch (FileNotFoundException e) {
LLog.e(e, "File not found");
} catch (IOException e) {
LLog.e(e, "File write failed");
}
return resultStr;
}
public static boolean deleteFile(String fileName, Context context) {
File dir = context.getFilesDir();
File file = new File(dir, fileName);
return file.delete();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/334680.html
