保存byte[]到本地文件
public static void writeFileToSDCard(@NonNull final byte[] buffer, String fileName, final boolean append,
final boolean autoLine) {
File file = new File(fileName);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
RandomAccessFile raf = null;
FileOutputStream out = null;
try {
if (append) {
//如果为追加则在原来的基础上继续写文件
raf = new RandomAccessFile(file, "rw");
raf.seek(file.length());
raf.write(buffer);
if (autoLine) {
raf.write("\n".getBytes());
}
} else {
//重写文件,覆盖掉原来的数据
out = new FileOutputStream(file);
out.write(buffer);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (raf != null) {
raf.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
读取文件内容
public static String readFile(String sourceDir, String fileName){
String fileContent = "";
File file = new File(sourceDir, fileName);
if (!file.exists()) return "";
BufferedReader reader = null;
try {
//设置将要打开的存储文件名称
//FileInputStream -> InputStreamReader ->BufferedReader
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = new String();
//读取每一行数据,并追加到StringBuilder对象中,直到结束
while ((line = reader.readLine()) != null) {
fileContent += line;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return fileContent;
}
读取Assets目录内容
public static String getFromAssets(String fileName, Context mContext) {
String content = null; //结果字符串
try {
InputStreamReader inputReader = new InputStreamReader(mContext.getResources().getAssets().open(fileName), "UTF-8" );
BufferedReader bufReader = new BufferedReader(inputReader);
String line="";
StringBuilder builder = new StringBuilder();
while((line = bufReader.readLine()) != null){
builder.append(line);
}
inputReader.close();
bufReader.close();
return builder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
复制Assets文件到本地目录
public static void copyAssetsToDst(Context context, String srcPath, String dstPath) {
try {
File outFile = new File(dstPath);
InputStream is = context.getAssets().open(srcPath);
FileOutputStream fos = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
int byteCount;
while ((byteCount = is.read(buffer)) != -1) {
fos.write(buffer, 0, byteCount);
}
fos.flush();
is.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}