Android 写入文件无效
Android write to file not working
Android我是初学者。我遇到了一个关于写入文件的问题。我想将我在表单中获得的输入保存到文件中。但是,我写的那段代码没有写在我的文件中。谁能帮帮我?
代码如下所示:
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuilder s = new StringBuilder();
s.append("Event name: " + editText1.getText() + "|");
s.append("Date: " + editText2.getText() + "|");
s.append("Details: " + editText3.getText() + "|");
File file = new File("D:\config.txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file, true), 1024);
out.write(s.toString());
out.newLine();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
所以,我有一个包含 3 个字段的表单:事件名称、日期和描述。这些我想保存到我的文件中。我应该提到我使用模拟器进行测试。
使用以下文件路径。它会将文件写入您的存储根文件夹。
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");
writeToFile("File content".getBytes(), file);
writeToFile
public static void writeToFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data);
}
finally {
if (bos != null) {
try {
bos.flush ();
bos.close ();
}
catch (Exception e) {
}
}
}
}
不要忘记在 AndroidManifest.xml
中添加以下权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
这是一个...几乎完成class,用于写入设备的模拟外部存储上的文档文件夹。
不要忘记添加清单的写入权限。
Android我是初学者。我遇到了一个关于写入文件的问题。我想将我在表单中获得的输入保存到文件中。但是,我写的那段代码没有写在我的文件中。谁能帮帮我? 代码如下所示:
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuilder s = new StringBuilder();
s.append("Event name: " + editText1.getText() + "|");
s.append("Date: " + editText2.getText() + "|");
s.append("Details: " + editText3.getText() + "|");
File file = new File("D:\config.txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file, true), 1024);
out.write(s.toString());
out.newLine();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
所以,我有一个包含 3 个字段的表单:事件名称、日期和描述。这些我想保存到我的文件中。我应该提到我使用模拟器进行测试。
使用以下文件路径。它会将文件写入您的存储根文件夹。
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");
writeToFile("File content".getBytes(), file);
writeToFile
public static void writeToFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data);
}
finally {
if (bos != null) {
try {
bos.flush ();
bos.close ();
}
catch (Exception e) {
}
}
}
}
不要忘记在 AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
这是一个...几乎完成class,用于写入设备的模拟外部存储上的文档文件夹。
不要忘记添加清单的写入权限。