将HTML String写入/返回文件到内部文件目录android

时间:2014-01-12 10:29:45

标签: android

您好我有一个包含html和css的字符串,我想将其作为文件加载到WebView中。所以我想在内部存储上创建一个目录,我真的不想将它存储在SDCard上,因为我正在保存的文件包含重要信息。然后我想创建一个mFile.html而不是该目录。最后一步是将文件返回加载到WebView中。有谁知道怎么做?

继承人到目前为止我所尝试过的事情

public static void writeFileToDirectory(Context activityContext, String writableString,String folderName, String fileName){


    File myDir = activityContext.getFilesDir();

    try {
        File secondFile = new File(myDir + "/" + folderName + "/", fileName);
        if (secondFile.getParentFile().mkdirs()) {
            secondFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(secondFile);

            fos.write(writableString.getBytes());
            fos.flush();
            fos.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        File secondInputFile = new File(myDir + "/html/", fileName);
        InputStream secondInputStream = new BufferedInputStream(new FileInputStream(secondInputFile));
        BufferedReader r = new BufferedReader(new InputStreamReader(secondInputStream));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line);
        }
        r.close();
        secondInputStream.close();
        Log.d("File", "File contents: " + total);
    } catch (Exception e) {
        e.printStackTrace();
    } 

1 个答案:

答案 0 :(得分:0)

try this

File myDir = activityContext.getFilesDir();

try {
    File secondFile = new File(myDir + "/" + folderName);
       if(!secondFile.exists())
        {
           secondFile.mkdir();
         }
        FileOutputStream fos = new FileOutputStream(secondFile.getAbsolutePath()+"/"+fileaName);

        fos.write(writableString.getBytes());
        fos.flush();
        fos.close();
    }
} catch (Exception e) {
    e.printStackTrace();
}