将字符串写入文件 [英] Write a string to a file
问题描述
我想在文件中写一些东西.我找到了以下代码:
I want to write something to a file. I found this code:
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文件.
如何检索包含字符串的文件?
The code seems very logical, but I can't find the config.txt file in my phone.
How can I retrieve that file which includes the string?
推荐答案
未指定路径,您的文件将保存在您的应用空间中(/data/data/your.app.name/
).
Not having specified a path, your file will be saved in your app space (/data/data/your.app.name/
).
因此,最好将文件保存到外部存储(不一定是SD卡,它可以是默认存储).
Therefore, you better save your file onto an external storage (which is not necessarily the SD card, it can be the default storage).
您可能需要阅读官方文档
综合:
将此权限添加到清单中:
Add this permission to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
它包含READ权限,因此也无需指定它.
It includes the READ permission, so no need to specify it too.
将文件保存在您指定的位置(该位置取自我的活鳕鱼,所以我确定它可以工作):
Save the file in a location you specify (this is taken from my live cod, so I'm sure it works):
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 Try like this (different path - a folder on the external storage):
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");
这篇关于将字符串写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!