文件大小在android中显示不正确

时间:2017-02-17 12:49:12

标签: android

我使用print writer和fileoutputstream使用以下函数在android异步任务中编写文件:

public static  void saveFileToExternalMemoryAsync(Context context,String fileName, String json)throws Exception{
       File AppPath = new File(Environment.getExternalStorageDirectory() + "/PDMA/DMAPPOutputs/");
       if (!AppPath.exists()) {
           AppPath.mkdirs();
       }
       File outputFile = new File(AppPath.getAbsolutePath() + "/" + fileName + ".dmapp");
       if (!outputFile.exists())
           outputFile.createNewFile();

       MediaScannerConnection.scanFile(context, new String[] {AppPath.toString(),outputFile.toString()}, null, null);
       FileOutputStream fileOutputStream = new FileOutputStream(outputFile, true);
       PrintWriter pw = new PrintWriter(fileOutputStream);
       try{
           pw.println(json);
           pw.flush();
           pw.close();
           fileOutputStream.flush();
           fileOutputStream.close();
       }catch (Exception e){
           e.printStackTrace();
       }finally{
           pw.flush();
           pw.close();
           fileOutputStream.flush();
           fileOutputStream.close();

           MediaScannerConnection.scanFile(context, new String[] {AppPath.toString(),outputFile.toString()}, null, null);
       }


   }

问题是,当我尝试通过将移动设备连接到mtp中的pc来复制此文件时,不会完全复制。如果我右键单击以查看其大小,则其小于实际值。现在如果在android中,我将此文件复制并粘贴到其他位置,比如在downloads文件夹中,大小正确,文件也完整。

可能是什么问题。

更新:

如果我使用fileOutputStream逐个写入字节,那么就会生成文件,但我必须关闭应用程序才能从pc访问该文件。

1 个答案:

答案 0 :(得分:0)

事实证明,通过在onPostExecute()的末尾添加this.cancel(true)解决了我的问题。