//创建文件并且写入数据(文件保存在sdcard的根目录)
public static void createTestFile() {
File SDFile = android.os.Environment.getExternalStorageDirectory();
File file = new File(SDFile.getAbsolutePath() + File.separator
+ "strategy.txt");
if (!file.exists()) {
try {
file.createNewFile();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), "UTF-8"));
bw.write("写入一行数据" + "\n");// "\n"是换行
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void readTestFile(){
File SDFile = android.os.Environment.getExternalStorageDirectory();
File file = new File(SDFile.getAbsolutePath() + File.separator+"strategy.txt");
try {
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
String str=br.readLine();//读取一行数据
br.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
public static void createTestFile() {
File SDFile = android.os.Environment.getExternalStorageDirectory();
File file = new File(SDFile.getAbsolutePath() + File.separator
+ "strategy.txt");
if (!file.exists()) {
try {
file.createNewFile();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), "UTF-8"));
bw.write("写入一行数据" + "\n");// "\n"是换行
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void readTestFile(){
File SDFile = android.os.Environment.getExternalStorageDirectory();
File file = new File(SDFile.getAbsolutePath() + File.separator+"strategy.txt");
try {
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
String str=br.readLine();//读取一行数据
br.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
需要添加到权限
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />