将字符串写入文件

Write a string to a file

我想向文件中写入一些内容。我找到了这段代码:

private void writeToFile(String data) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

代码看起来很合乎逻辑,但我在 phone.
中找不到 config.txt 文件 如何检索包含该字符串的文件?

没有指定 路径,您的文件将保存在您的应用 space (/data/data/your.app.name/) 中。

因此,您最好将文件保存到外部存储设备(不一定是SD卡,可以是默认存储设备)。

您可能想深入了解这个主题,阅读 official docs

合成中:

将此权限添加到您的清单:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

包含READ权限,所以不用再指定。

将文件保存在您指定的位置(这是从我的 live cod 中获取的,所以我确定它可以工作):

public void writeToFile(String data)
{
    // Get the directory for the user's public pictures directory.
    final File path =
        Environment.getExternalStoragePublicDirectory
        (
            //Environment.DIRECTORY_PICTURES
            Environment.DIRECTORY_DCIM + "/YourFolder/"
        );

    // Make sure the path directory exists.
    if(!path.exists())
    {
        // Make it, if it doesn't exit
        path.mkdirs();
    }

    final File file = new File(path, "config.txt");

    // Save your stream, don't forget to flush() it before closing it.

    try
    {
        file.createNewFile();
        FileOutputStream fOut = new FileOutputStream(file);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append(data);

        myOutWriter.close();

        fOut.flush();
        fOut.close();
    }
    catch (IOException e)
    {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

[编辑] OK 像这样尝试(不同的路径 - 外部存储上的文件夹):

    String path =
        Environment.getExternalStorageDirectory() + File.separator  + "yourFolder";
    // Create the folder.
    File folder = new File(path);
    folder.mkdirs();

    // Create the file.
    File file = new File(folder, "config.txt");

此方法将文件名和数据字符串作为输入并将它们转储到 SD 卡上的文件夹中。 如果需要,您可以更改文件夹的名称。

return 类型是 Boolean 取决于 FileOperation 的成功或失败。

重要提示:尝试在异步任务中执行此操作,因为 FIle IO 会导致主线程出现 ANR。

 public boolean writeToFile(String dataToWrite, String fileName) {

            String directoryPath =
                    Environment.getExternalStorageDirectory()
                            + File.separator
                            + "LOGS"
                            + File.separator;

            Log.d(TAG, "Dumping " + fileName +" At : "+directoryPath);

            // Create the fileDirectory.
            File fileDirectory = new File(directoryPath);

            // Make sure the directoryPath directory exists.
            if (!fileDirectory.exists()) {

                // Make it, if it doesn't exist
                if (fileDirectory.mkdirs()) {
                    // Created DIR
                    Log.i(TAG, "Log Directory Created Trying to Dump Logs");
                } else {
                    // FAILED
                    Log.e(TAG, "Error: Failed to Create Log Directory");
                    return false;
                }
            } else {
                Log.i(TAG, "Log Directory Exist Trying to Dump Logs");
            }

            try {
                // Create FIle Objec which I need to write
                File fileToWrite = new File(directoryPath, fileName + ".txt");

                // ry to create FIle on card
                if (fileToWrite.createNewFile()) {
                    //Create a stream to file path
                    FileOutputStream outPutStream = new FileOutputStream(fileToWrite);
                    //Create Writer to write STream to file Path
                    OutputStreamWriter outPutStreamWriter = new OutputStreamWriter(outPutStream);
                    // Stream Byte Data to the file
                    outPutStreamWriter.append(dataToWrite);
                    //Close Writer
                    outPutStreamWriter.close();
                    //Clear Stream
                    outPutStream.flush();
                    //Terminate STream
                    outPutStream.close();
                    return true;
                } else {
                    Log.e(TAG, "Error: Failed to Create Log File");
                    return false;
                }

            } catch (IOException e) {
                Log.e("Exception", "Error: File write failed: " + e.toString());
                e.fillInStackTrace();
                return false;
            }
        }

写一个简化的文本文件:

private void writeToFile(String content) {
    try {
        File file = new File(Environment.getExternalStorageDirectory() + "/test.txt");

        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter writer = new FileWriter(file);
        writer.append(content);
        writer.flush();
        writer.close();
    } catch (IOException e) {
    }
}

您可以在文件的logData中写入完整的数据

文件将在下载目录中创建

This is only for Api 28 and lower .

This will not work on Api 29 and higer

@TargetApi(Build.VERSION_CODES.P)
public static File createPrivateFile(String logData) {
    String fileName = "/Abc.txt";
    File directory = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/");
    directory.mkdir();
    File file = new File(directory + fileName);
    FileOutputStream fos = null;
    try {
        if (file.exists()) {
            file.delete();
        }
        file = new File(getAppDir() + fileName);
        file.createNewFile();
        fos = new FileOutputStream(file);
        fos.write(logData.getBytes());
        fos.flush();
        fos.close();
        return file;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}