如何将文件从应用程序写入文件夹Test?

时间:2019-04-15 06:22:32

标签: android

我在内部存储器的根目录中创建了Test文件夹。如何从应用程序将文件写入此文件夹Test? (例如whatsapp。)

public class ReadWriteFile {
    public static void ReadWriteFile(String text, Context context) {
        DateFormat timeFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss", Locale.getDefault());
        Date currentDate = new Date();
        text = timeFormat.format(currentDate) + text;
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("/test/test.log", Context.MODE_WORLD_WRITEABLE));
            outputStreamWriter.write(text);
            outputStreamWriter.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

2 个答案:

答案 0 :(得分:1)

使用此代码,您可以创建自己的目录

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder_Name";
        File dir = new File(path);
        try {
            if (!dir.exists())
                dir.mkdir();
        } catch (Exception e) {
            e.printStackTrace();
        }

并使用它保存您的文件insdie

String targetPdf = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder_Name/" + filename;

并保存文件

new FileOutputStream(targetPdf)

希望这会对您有所帮助。

答案 1 :(得分:0)

在文件夹中写入文本文件的示例:

File mDir = new File(getCacheDir(), "yourFolder");
mDir.mkdir();


try {
        String root_path = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/MyFolder/";
        File root = new File(root_path);
        if (!root.exists()) {
            root.mkdirs();
        }
        File f = new File(root_path + "mttext.txt");
        if (f.exists()) {
            f.delete();
        }
        f.createNewFile();

        FileOutputStream out = new FileOutputStream(f);

        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }