AsyncTask:不将数据写入文件

时间:2015-04-13 14:08:36

标签: java android file android-asynctask

我对Android编程很新,我一直在提供一些代码来解决一个我现在似乎无法解决的问题。

我有一个AsyncTask试图将一些数据保存到设备内部存储器上的文件中。文件已创建,但填充了0个字节

public void exportFile(final Context mContext, boolean debug) {

    try {
        final String path = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/DroidP";
        File dir = new File(path);
        dir.mkdirs();

        final File file = new File(dir, "Droid_export.txt");

        if (file.exists()) {
            file.delete();                          
        }

        file.createNewFile();

        final FileWriter out = new FileWriter(file,true);



        final int totalLines = recordsIdList.size();
        new AsyncTask<Void, String, Void>() {
            ProgressDialog progressDialog;

            @Override
            protected Void doInBackground(Void... arg0) {
                try {



                    List<byte[]> mainBuffer = new ArrayList<byte[]>();

                    int i = 0;
                    int size = 0;

                    for (Integer r : recordsIdList) {
                        Log.i("test", db.getRecord(r).toExportSQL());

                        byte[] buffer = db.getRecord(r).toExportSQL().getBytes(); 
                        mainBuffer.add(buffer);
                        size += buffer.length;

                        publishProgress("Writing " + (i++) + " from "+ totalLines);
                    }

                    int pos = 0;
                    char[] outBuffer = new char[size];
                    for(byte[] chunk : mainBuffer) {
                        for(i=0;i<chunk.length;i++) {
                            outBuffer[pos] = (char)chunk[i];
                            pos++;
                        }                           
                    }

                    out.write(outBuffer);

                    out.flush();



                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
      }

            @Override
            protected void onProgressUpdate(String... progress) {
                progressDialog.setMessage(progress[0]);
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                progressDialog.dismiss();
            }

            @Override
            protected void onPreExecute() {
                progressDialog = ProgressDialog.show(mContext,
                        "Exporting file", "", true);
            }
        }.execute((Void) null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file.getAbsoluteFile()));
        sendBroadcast(intent);
    } catch (Exception e) {

    }
}

当我查看日志时,我能够看到我正在尝试保存到文件中的数据,这是正确的,但是一旦AsyncTask完成,就会创建一个0字节的文件。我是遗漏了什么?请记住,我是Android编程的新手。

1 个答案:

答案 0 :(得分:2)

我没有测试您的错误,但您可以通过跳过bytechar转换并将文件处理移到异步任务中来简化您的问题。许多人建议。

尝试这样的事情:

private Boolean isExporting = false;

public void exportFile(final Context mContext, boolean debug) {
    if (!isExporting) {
        isExporting = true;
        new AsyncTask<Void, String, Void>() {
            ProgressDialog progressDialog;

            @Override
            protected Void doInBackground(Void... arg0) {
                try {
                    // read data into byte array
                    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int i = 0;
                    for (Integer r : recordsIdList) {
                        byte[] buffer = db.getRecord(r).toExportSQL().getBytes();
                        Log.i("test", new String(buffer));
                        baos.write(buffer);
                        publishProgress("Writing " + (i++) + " from " + totalLines);
                    }
                    baos.close();
                    // write data to file
                    final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DroidP";
                    final File dir = new File(path);
                    dir.mkdirs();
                    final File file = new File(dir, "Droid_export.txt");
                    file.createNewFile();
                    final FileOutputStream fos = new FileOutputStream(file);
                    fos.write(baos.toByteArray());
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(String... progress) {
                progressDialog.setMessage(progress[0]);
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                isExporting = false;
                progressDialog.dismiss();
            }

            @Override
            protected void onPreExecute() {
                progressDialog = ProgressDialog.show(mContext,
                        "Exporting file", "", true);
            }
        }.execute();
    }
}