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 "";
}
}

原文地址:https://www.cnblogs.com/shijiaoyun/p/5731725.html