1.字符串写入文件中
/**
* 获取目标文件的里面的String
*
* @param targetPath
* 目标路径
* @param content
* 写入的内容
* @return
*/
public static void writeSetingsToFile(String targetPath, String content,FileUtilListener fileUtilListener) {
File file = new File(targetPath);
Log.d(TAG, " write file exists = "+file.exists());
if (file.exists()) {
file.delete();
} else {
fileUtilListener.writeSettingFileFailed();
}
File parentFile = file.getParentFile();
Log.d(TAG, " write parentFile exists = "+parentFile.exists());
if (!parentFile.exists()) {
parentFile.mkdirs();
}
try {
boolean createNewFile = file.createNewFile();
Log.d(TAG, " write createNewFile = "+createNewFile);
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(content.getBytes("utf-8"));
fos.flush();
fos.close();
Log.d(TAG, " write success ...");
fileUtilListener.writeSettingFileSuccess();
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, " write failed ...");
fileUtilListener.writeSettingFileFailed();
}
}
备注:
//如何实现FileOutputStream类,实现换行写入和追加写入的解决办法
//FileOutputStream fos2 = new FileOutputStream(“fos3.txt”, true);// 第二個参数为true表示程序每次运行都是追加字符串在原有的字符上
// 写数据
for (int x = 0; x < 10; x++) {
fos2.write(("hello" + x).getBytes());
fos2.write("\r\n".getBytes());// 写入一个换行
}
// 释放资源
fos2.close();
2.如何读取SD卡文件中的数据
/**
* 创建设置文件
*
* @param path
* @param values
* @return
*/
public static String readSettingFromFile(String path) {
File file = new File(path);
FileInputStream fis = null;
BufferedReader bufferReader = null;
StringBuffer sb = null;
Log.d(TAG, "read file exites = "+file.exists());
if (file.exists()){
try {
fis = new FileInputStream(file);
bufferReader = new BufferedReader(new InputStreamReader(fis));
sb = new StringBuffer();
String line = "";
Log.d(TAG, "read bufferReader = "+bufferReader);
try {
while ((line = bufferReader.readLine()) !=null){
sb.append(line);
Log.d(TAG, "read line = "+line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bufferReader.close();
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else{
return null;
}
Log.d(TAG, "read sb.toString() = "+sb.toString());
return sb.toString();
}