文件相关操作
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) {
}
}
}
3、文件拷贝
public static void copyFolder(String srcDir, String destDir) {
Log.d("wujiang", "copyFolder: srcDir = " + srcDir);
Log.d("wujiang", "copyFolder: destDir = " + destDir);
try {
File destFile = new File(destDir);
if (destFile.exists()) {
destFile.delete();
}
destFile.mkdir();
File srcFile = new File(srcDir);
String[] files = srcFile.list();
File temp;
for(String file : files) {
Log.d(TAG, "copyFolder: file = " + file);
if (srcDir.endsWith(File.separator)) {
temp = new File(srcDir + file);
} else {
temp = new File(srcDir + File.separator + file);
}
if (temp.isDirectory()) { //如果是子文件夹
copyFolder(srcDir + File.separator + file, destDir + File.separator + file);
} else if (!temp.exists()) {
Log.e(TAG, "copyFolder: oldFile not exist.");
return;
} else if (!temp.isFile()) {
Log.e(TAG, "copyFolder: oldFile not file.");
return;
} else if (!temp.canRead()) {
Log.e(TAG, "copyFolder: oldFile cannot read.");
return;
} else {
FileInputStream fileInputStream = new FileInputStream(temp);
FileOutputStream fileOutputStream = new FileOutputStream(destDir + File.separator + temp.getName());
byte[] buffer = new byte[1024];
int byteRead;
while ((byteRead = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, byteRead);
}
fileInputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
}
}
} catch (Exception e) {
Log.e(TAG, "error msg: " + e.getMessage());
} finally {
}
}