Fac*_*pai 2 android android-file
我正在尝试为 Android 编写一个应用程序,我需要从服务器保存 resposne,我设法通过将其保存在此路径中的 txt 文件中来做到这一点:
String path= "/storage/emulated/0/Android/data/com.example.simone.pizzino/files/response.txt";
final File file = new File(path);
在我朋友的手机上测试,他看不到那个路径下的文件夹,他的路径类似于data/data/"packageName"
,它也不适用于 Android Studio 中的模拟器。我的手机是运行 7.1 库存 rom 的 Nexus 5X。我的朋友使用 6.1 扎根。有没有办法获得应用程序文件夹的动态路径而不必将其声明为常量?
抱歉,如果已经问过这个问题,但我找不到解决我的问题的方法。
小智 5
您要做的第一件事是在清单文件中添加访问外部存储的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)
在内部存储上保存文件
File file = new File(context.getFilesDir(), filename);
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
public File getTempFile(Context context, String url) {
File file;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
} catch (IOException e) {
// Error while creating file
}
return file;
}
Run Code Online (Sandbox Code Playgroud)
在外部存储上保存文件
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12879 次 |
最近记录: |