1

嗨,我需要从 url 下载文件并保存在内部存储中,因此下载过程在异步任务中运行。首先,我尝试使用异步任务在文件中写入一个字符串,但给了我错误:无法创建 oat 文件。相同的代码无需任务即可工作,所以我的问题是我必须将文件下载到外部存储中,然后移入内部?

    private void writeInFile() {
    FileOutputStream output = null;
    String text = "TEXT";
    try {
        output = openFileOutput("nameFile.abc",Context.MODE_PRIVATE);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }


    try {
        output.write(text.getBytes());
        output.flush();
        output.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

但是,如果我在扩展 AsyncTask 的类的 doInBackground 中调用此函数,则会收到错误消息。

    LicenzaTask mt = new LicenzaTask(this);
    mt.execute();


public class LicenzaTask extends AsyncTask<Void, Void, Void> {

private Context mContext;

public LicenzaTask(MainActivity mainActivity) {
    mContext = mainActivity;
}

@Override
protected Void doInBackground(Void... voids) {

    modifyFile();

    return null;
}


private void modifyFile() {
    File file = new File(mContext.getFilesDir() + "nome.abc");
    String text = "text";
    BufferedWriter output = null;
    try {
        output = new BufferedWriter(new FileWriter(file));
        output.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
            }
        }
        }
    }
4

0 回答 0