public class TextUtil {
/**
* 按行读取文本文件
*
* @param fileName
* @param lineValue
* @throws IOException
*/
public static void read(String fileName, Consumer<String> lineValue) throws IOException {
File file = new File(fileName);
InputStreamReader inputStreamReader = null;
BufferedReader br = null;
try {
if (!file.exists()){
throw new FileNotFoundException("未找到文件:".concat(fileName));
}
inputStreamReader = new InputStreamReader(new FileInputStream(file));
br = new BufferedReader(inputStreamReader);
String line;
while (null != (line = br.readLine())){
if (!"".equals(line)){
lineValue.accept(line);
}
}
}finally {
if (null != br){
br.close();
}
if (null != inputStreamReader){
inputStreamReader.close();
}
}
}
/**
* 文件中写入文本
*
* @param fileName
* @param text
*/
public static void write(String fileName, String text){
File file = new File(fileName);
try {
FileWriter fw = new FileWriter(file);
fw.write(text);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
10-23