文件相关操作
1、读文件,一行一行的读
public static void readFile(File file) {
InputStream instream = null;
try {
instream = new FileInputStream(file);
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
//分行读取
while ((line = buffreader.readLine()) != null) {
Log.d("readFile: line str = ", line);
}
}
} catch (java.io.FileNotFoundException e) {
Log.d("readFile", "The File doesn't exist.");
} catch (IOException e) {
Log.d("readFile", e.getMessage());
} finally {
try {
if (instream != null) {
instream.close();
}
} catch (IOException e) {
}
}
}
2、一行一行的写
private void writeFile(File file) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
List<String> strList = new ArrayList<>();
strList.add("string 1");
strList.add("string 2");
strList.add("string 3");
strList.add("string 4");
strList.add("string 5");
strList.add("string 6");
for (String str : strList) {
String writeLine = str + "\n";
fileOutputStream.write(writeLine.getBytes());
}
} catch (java.io.FileNotFoundException e) {
} catch (IOException e) {
Log.d(TAG, "writeFile" + e.getMessage());
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
}
}
}
来源:CSDN
作者:wujiang_android
链接:https://blog.csdn.net/wujiang_android/article/details/104440662