我可以创建文件但不能写入它

时间:2013-09-08 14:00:23

标签: android file-io

有人可以看看这段代码吗,让我知道我做错了什么?这是一个简单的函数,它将一个字符串作为参数,将其用作文件名,并在其末尾添加“.txt”。

该函数检查文件是否存在,如果不存在则创建它,然后将两行文本写入文件。一切似乎都在工作,文件在SD卡上成功创建。但是,完成所有操作后,文件为空(并且大小为0字节)。

我怀疑这是显而易见的,我忽视了。

public void writeFile(String fileName) {
    String myPath = new File(Environment.getExternalStorageDirectory(), "SubFolderName");
    myPath.mkdirs();

    File file = new File(myPath, fileName+".txt");

    try {
        if (!file.exists()) {
            if (!file.createNewFile()) {
                Toast.makeText(this, "Error Creating File", Toast.LENGTH_LONG).show();
                return;
            }
        }

        OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
        writer.append("First line").append('\n');
        writer.append("Second line").append('\n');

        writer.close();
    }
    catch (IOException e) {
        // Do whatever
    }
}

3 个答案:

答案 0 :(得分:1)

您好我会告诉您我使用的完整代码,效果很好。 我不使用

 new OutputStreamWriter() 

我用

new BufferedWriter()

这是我的代码段

public void writeToFile(Context context, String fileName, String data) {

    Writer mwriter;

    File root = Environment.getExternalStorageDirectory();
    File dir = new File(root.getAbsolutePath() + File.separator + "myFolder");

    if (!dir.isDirectory()) {
        dir.mkdir();
    }

    try {
        if (!dir.isDirectory()) {
            throw new IOException(
                "Unable to create directory myFolder. SD card mounted?");
        }
        File outputFile = new File(dir, fileName);
        mwriter = new BufferedWriter(new FileWriter(outputFile));
        mwriter.write(data); // DATA WRITE TO FILE
        Toast.makeText(context.getApplicationContext(),
            "successfully saved to: " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
        mwriter.close();
    } catch (IOException e) {
        Log.w("write log", e.getMessage(), e);
        Toast.makeText(context, e.getMessage() + " Unable to write to external storage.",Toast.LENGTH_LONG).show();
        }
}

-- Original Code --

答案 1 :(得分:1)

那个人需要一段时间才能找到答案。 javadocs here让我走上正轨。 它说:

Parameters
  • name The name of the file to open; can not contain path separators.
  • mode Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_APPEND to append to an existing file, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
  • 如果该文件不存在,则会创建该文件,但该文件是在私有应用空间中创建的。您可以使用File.createNewFile()在SD卡上的某个位置创建文件,但是当您执行context.openFileOutput()时,它会在私有应用空间中创建始终私有文件。

    编辑:这是我的代码。我通过编写和读取行来扩展你的方法并打印我对logcat的所有内容。

    <pre>
        public void writeFile(String fileName) {
        try {
            OutputStreamWriter writer = new OutputStreamWriter(
                    getContext().openFileOutput(fileName + ".txt", Context.MODE_PRIVATE));
            writer.append("First line").append('\n');
            writer.append("Second line").append('\n');
    
            writer.close();
        }
        catch (IOException e) {
            Log.e("STACKOVERFLOW", e.getMessage(), e);
            return;
            // Do whatever
        }
    
        // Now read the file
        try {
            BufferedReader is = new BufferedReader(
                    new InputStreamReader(
                            getContext().openFileInput(fileName + ".txt")));
            for(String line = is.readLine(); line != null; line = is.readLine())
                Log.d("STACKOVERFLOW", line);
    
            is.close();
        } catch (IOException e) {
            Log.e("STACKOVERFLOW", e.getMessage(), e);
            return;
            // Do whatever
        }
    }
    

    答案 2 :(得分:0)

    Context.MODE_PRIVATE

    中将模式从Context.MODE_APPEND更改为openFileOutput()

    MODE_APPEND

    MODE_PRIVATE

    而不是

    OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
    

    使用

    OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_APPEND));
    

    更新:

    <强> 1

    FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
    
    OutputStreamWriter writer = new OutputStreamWriter(osr);
    BufferedWriter fbw = new BufferedWriter(writer);
                fbw.write("First line");
                fbw.newLine();
                fbw.write("Second line");
                fbw.newLine();
                fbw.close();
    

    或2。

    private void writeFileToInternalStorage() {
              FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
              String eol = System.getProperty("line.separator");
              BufferedWriter fbw = null;
              try {
                  OutputStreamWriter writer = new OutputStreamWriter(osr);
                  fbw = new BufferedWriter(writer);
                  fbw.write("First line" + eol);
                  fbw.write("Second line" + eol);           
    
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                if (fbw != null) {
                try {
                    fbw.close();
                } catch (IOException e) {
                  e.printStackTrace();
                }
                }
              }
            }