我想创建一个包含字符串的文本文件。
String string = "hello!";
File file = new File(Environment.getExternalStorageDirectory(),"test.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(string.getBytes());
fos.close();
我拥有相应的权限。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.latorre"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />...
但是没有创建该文件。为什么呢?
答案 0 :(得分:1)
public void writefile(String word1)
try {
String path = sdCard.getAbsolutePath() + "/";
File logFile = new File(path + "test.txt");
if (!logFile.exists()) {
logFile.createNewFile();
}
// BufferedWriter for performance, true to set append to file
FileWriter fw = new FileWriter(logFile, true);
BufferedWriter buf = new BufferedWriter(fw);
buf.append(word1);
buf.newLine();
buf.flush();
}
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
答案 1 :(得分:0)
String string = "hello!";
File file = new File(Environment.getExternalStorageDirectory() + "/", "test.txt");
if (!file.exists()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file, true);
fos.write(string.getBytes());
fos.close();