【问题标题】:OutputWriter Java or AndroidOutputWriter Java 或 Android
【发布时间】:2012-03-22 18:53:28
【问题描述】:

我想将数据写入输出文件并将其保存在移动设备或计算机硬盘上。我可以让我的代码在下面工作,但必须在一个步骤中创建目录,然后在另一个步骤中创建文件。有没有更有效的方法来编写代码,必须在写入文件之前创建一个不存在的目录?

谢谢

StringBuilder Path = new StringBuilder();
    Path.append(Environment.getExternalStorageDirectory().toString());

    String filename = "test.txt";
    String test_text = "Date, Item, Quantity, Description,";
    File file = new File(Path.toString()+"/" +"Test Folder2/");
    file.mkdirs();
    FileOutputStream file_os = null;
    try {
        File file2 = new File(Path.toString()+"/" +"Test Folder2", filename);
        file_os = new FileOutputStream(file2);
        OutputStreamWriter osw = new OutputStreamWriter(file_os);

        try {
            osw.write(test_text);
        } catch (IOException e) {

            e.printStackTrace();
        }   
        try {
            osw.close();
        } catch (IOException e) {

            e.printStackTrace();
        }

    } catch (FileNotFoundException e) {
        Toast.makeText(QuizSettingsActivity.this, Path.toString(),
                Toast.LENGTH_LONG).show();

    };

【问题讨论】:

  • 只要目录不存在,我想你就得创建目录...

标签: java android io outputstream


【解决方案1】:
String FILENAME = "test";
String string = "Date, Item, Quantity, Description,";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

有关在外部存储上保存文件的更多详细信息,请点击以下链接:.http://developer.android.com/guide/topics/data/data-storage.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多