package cn.itoak;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Project:CodeFragment
* FullPath:cn.itoak.ReadFileByLineAndWrite
* Date:2019/9/20
* Time:14:07
* Description:按行读取并写文件
*
* @author itoak
* @version 1.0
*/
public class ReadFileByLineAndWrite {
/**
* 按行读取
*
* @param pathName 文件路径
* @return 行结果
*/
public static List<String> readFile(String pathName) throws IOException {
List<String> strings = new ArrayList<>();
File file = new File(pathName);
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
BufferedReader bf = new BufferedReader(inputStreamReader);
String str;
while ((str = bf.readLine()) != null) {
strings.add(str);
}
//关闭流
bf.close();
inputStreamReader.close();
return strings;
}
/**
* 写入文件
* @param strings 内容
* @param pathName 生成文件路径
*/
public static void writeFile(List<String> strings, String pathName) throws IOException {
FileWriter fileWriter = new FileWriter(new File(pathName));
BufferedWriter bw = new BufferedWriter(fileWriter);
for (String str : strings){
bw.write(str + "\t\n");
}
//关闭流
bw.close();
fileWriter.close();
}
public static void main(String[] args) throws IOException {
//读文件
List<String> strings = readFile("E:/a.txt");
//写文件
writeFile(strings, "E:/b.txt");
}
}
2019年12月02日更新:以上是笔者自己写的,其实Apache的common-io包下已经封装了FileUtils工具类,包含以上功能
- 依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
- 使用示例
public static void main(String[] args) throws IOException {
List<String> list = FileUtils.readLines(new File("/data"), Charset.defaultCharset());
FileUtils.writeLines(new File("/data1"), list);
}