package com.rc114.scanner;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;
public class FileHelper {
public static String combinePath(String path1, String path2) {
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
/**
* 读取文件
*
* @param filepath 文件路径
*/
public static String readFile(String filepath) {
String encoding = "UTF-8";
return readFile(filepath, encoding);
}
/**
* 读取文件,指定编码
*
* @param filepath 文件路径
*/
public static String readFile(String filepath, String encoding) {
try {
filepath = URLDecoder.decode(filepath, "utf-8");
File file = new File(filepath);
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
FileInputStream in = new FileInputStream(file);
in.read(filecontent);
in.close();
return new String(filecontent, encoding);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* 将字符串写入文件
*
* @param filepath
* @param text
* @param isAppend
*/
public static void writeFile(String filepath, String text, boolean isAppend) {
try {
filepath = URLDecoder.decode(filepath, "utf-8");
File file = new File(filepath);
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream f = new FileOutputStream(filepath, isAppend);
f.write(text.getBytes());
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeFile(String filepath, String text, String encodeing) {
try {
filepath = URLDecoder.decode(filepath, "utf-8");
File file = new File(filepath);
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(filepath), encodeing);
writer.append(text);
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Android 文件读写辅助类
分类:Adnroid
发布:2023-02-08
来源:本站
浏览:82 次
如果觉得文章对您有帮助,您可以对我进行打赏 ¥1.09 元(金额随机^_^,每次刷新金额不同)。
请使用支付宝扫码支付
留言评论
*称 呼: | |
*联系方式: | 方便与您取得联系,推荐使用邮箱。 |
*内 容: | |
已有评论
暂无数据 |