java文件读写工具类

依赖jar:commons-io.jar

1、写文件

// by FileUtils
List<String> lines = FileUtils.readLines(file, "UTF-8");

// by IOUtils
List<String> lines = IOUtils.readLines(new FileInputStream(file), "UTF-8");

2、读取文件

// by FileUtils
FileUtils.writeLines(file, "UTF-8", lines);

// by IOUtils
IOUtils.writeLines(lines, null, new FileOutputStream(file));

 

特殊需求:FileUtils/IOUtils中写入文本的方法看上去都是只能一次性的批量写入多行,并覆盖原有的文本,如果我们需要单行写入怎么办呢,

其实在IOUtils中是提供了这样的方法的,只不过比较隐晦而已:

try {
OutputStream os = new FileOutputStream(file, true);
IOUtils.writeLines(lines, null, os, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}

其实就是在初始化FileOutputStream的时候 ,第二个参数append设为true就可以了。

 

 

IOUtils工具类读

List<String> lines = IOUtils.readLines(LockIP.class.getClassLoader().getResourceAsStream("warningType.data"), "UTF-8");

FileUtils工具类读写:

 

File config=new File("device-config.ini");
List<String> lines=new ArrayList<String>();
if(config.exists()){
try {
lines=FileUtils.readLines(config, "UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
lines.add(name+":"+deviceIds);
try {
FileUtils.writeLines(config, "UTF-8", lines);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

 

properties文件修改和读取:

/**
* 设置properties文件中的key-value
* @param fileName
* @param key
* @param value
*/
public static void setPropertiesValues(String fileName,String key, String value){
String path = CommonUtil.class.getResource("/").getPath() + fileName;
Properties props=new Properties();
FileOutputStream fos = null;
try {
props.load(CommonUtil.class.getClassLoader().getResourceAsStream(fileName));
// 修改属性值
props.setProperty(key, value);
System.out.println(path);
File file = new File(path);
if(!file.exists()){
return ;
}
// 文件输出流
fos = new FileOutputStream(file);
// 将Properties集合保存到流中
props.store(fos, "update " + key + "=" + value);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(fos != null){
try {
// 关闭流
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* 通过key值获取properties文件中的设定值
* @param fileName
* @param key
* @return
*/
public static String getPropertiesValues(String fileName,String key){
Properties props=new Properties();
try {
props.load(CommonUtil.class.getClassLoader().getResourceAsStream(fileName));
// 获取属性值
String str = props.getProperty(key,"1");
return str;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值