0

公共静态无效写入(字节[] 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 线程的推荐方法,一个真实世界的例子将不胜感激

提前致谢

4

1 回答 1

0
(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
     }
}
于 2019-12-07T17:19:08.847 回答