有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java保存Android文本文件不会在文件中写入文本

这段代码的目标是保存一个名为test的文本文件。ABCPrint文件夹中的txt
它当前正在创建文件夹并创建测试。txt文件,但当我打开文件时,里面没有文本。我已经尝试了一切,从表面上看,这不是许可问题

是否有人认为下面的代码有任何错误,会阻止它将字符串写入文件

try {

    File testFolder = new File(Environment.getExternalStorageDirectory(),"ABCPrint");
    testFolder.mkdirs();

    File file = new File(testFolder, "test.txt");
    boolean isnew =file.createNewFile();

    FileOutputStream fileOut = openFileOutput(file.getName(), Context.MODE_WORLD_WRITEABLE);
    OutputStreamWriter outputWriter = new OutputStreamWriter(fileOut);

    outputWriter.write("Hello World!");
    outputWriter.write("\n");
    outputWriter.flush();
    outputWriter.close();
    fileOut.flush();
    fileOut.close();

} catch (Exception e) {

    Log.i("Error", "Here", e);
}

共 (1) 个答案

  1. # 1 楼答案

    每次你调用这行代码,你的文件就会被再次创建。还有另一种简单的方法:

    File testFolder = new File(
                Environment.getExternalStorageDirectory(),
                "ABCPrint");
    if (!testFolder.exists())
    {
        try
        {
            testFolder.createNewFile();
        } 
        catch (IOException e){
            e.printStackTrace();
        }
    }
    try
    {
        //BufferedWriter for performance, true to set append to file flag
        BufferedWriter buf = new BufferedWriter(new FileWriter(testFolder, true)); 
        buf.append("Hello World!");
        buf.newLine();
        buf.close();
    }
    catch (IOException e){
        e.printStackTrace();
    }
    

    祝你好运