将字符串写入文件

时间:2016-02-18 12:47:28

标签: android streamwriter

我想写一些文件。我找到了这段代码:

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());
    } 
}

代码似乎非常符合逻辑,但我在手机中找不到config.txt文件 如何检索包含字符串的文件?

4 个答案:

答案 0 :(得分:39)

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

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

您可能希望通过阅读official docs

来深入研究这一主题

在综合中:

将此权限添加到您的Manifest:

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

它包含READ权限,因此无需另外指定。

将文件保存在您指定的位置(这取自我的活鳕鱼,所以我确定它有效):

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());
    } 
}

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

    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");

答案 1 :(得分:2)

编写一个简化的文本文件:

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) {
    }
}

答案 2 :(得分:0)

此方法采用文件名称&amp; data String作为输入并将它们转储到SD卡上的文件夹中。 如果需要,您可以更改文件夹的名称。

返回类型为布尔值,具体取决于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;
            }
        }

答案 3 :(得分:0)

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

该文件将在Downlaods目录中创建

这仅适用于Api 28及更低版本。

这不适用于Api 29和更高版本

@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;
}
相关问题