android-permissions - 什么是 Android 中的严格模式策略违规
问题描述
公共静态无效写入(字节[] aInput,字符串aOutputFileName,字符串dirName){
(new File(dirName)).mkdir();
try {
OutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(dirName + "/" + aOutputFileName));
output.write(aInput);
} finally {
output.close();
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
} catch (IOException ex) {
System.out.println(ex);
}
}
上面的代码来自我正在使用的库,它应该创建一个输出文件并向其写入一个字节数组。我检查了 logcat 并看到了 Strict Mode Policy 违反 Write.toDisk。我知道我的问题应该是什么:(1)严格模式是否会阻止您在主线程上进行磁盘读写?(2) 这是否意味着文件或文件夹实际上并未创建?(3) 那么我将如何在我的应用程序中创建一个不会触发此操作的文件夹或文件?(4) 什么是处理磁盘读/写主 ui 线程的推荐方法,一个真实世界的例子将不胜感激
提前致谢
解决方案
(1) It turns out that Strict mode doesn't actually prevent you from making writes to the disk it just gives a warning. From Android Developer "StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them". https://developer.android.com/reference/android/os/StrictMode
(2) The files were actually being created it's just that I was just not familiar with writing and reading from disk
(3) There are numerous ways to go about creating files (i) first you get a hold of a file directory to write the file to:
context.getFilesDir()
(ii) then you get an outputstream writer (iii) then you write out the data with the writer
public void makeFile(String filename){
//Create temp file for filename
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(filename));
fos.write(filename.getBytes());//Write the contents of the file to app folder
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
(iv) finally you close the outputstream writer
(4) The recommended way is to use either an AsyncTask or some other background running class like FutureTask or to use Threads or Runnable:
public class DownloadFileThread implements Runnable{
public void run(){
//your code here
}
}
推荐阅读
- apache-spark - pyspark - 检索 rdd 的第一个元素 - top(1) 与 first()
- python-3.x - Jupyter Notebook Python3 支持
- python-3.x - 从注解返回的字典列表中获取name键的值,然后按名称排序?
- javascript - Ajax 表单未收到来自 PHP 表单处理程序的响应
- c# - 使用方法的结果作为另一个方法中的参数
- botframework - 无法在轮播英雄卡中显示项目
- mysql - 合并 2 选择与限制偏移没有关系 SQL
- matlab - 如何在 Matlab 中创建大矩阵
- javascript - 在ionic 3中打开相机后,我想捕获多张图像
- php - 路由没有参数