package com.wx;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* FileName: FileUtil
* Author: mohe
* Date: 2021/11/5 16:29
* Description:
*/
public class FileUtil {
private final File file;
//要写入的String文本
private String a;
//文件路径
private final String path;
public FileUtil(String path, String a) throws IOException {
file = new File(path);
this.a = a;
this.path = path;
}
public FileUtil(String path) throws IOException {
file = new File(path);
this.path = path;
}
public void createFile() throws IOException {
file.delete();
file.createNewFile();
}
public void writeFile(String a) throws IOException {
FileWriter f = new FileWriter(file, true);
f.write(a);
f.close();
}
//读取文件写入list
public List<String> readFile() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
List<String> list = new ArrayList<>();
String readStr;
while ((readStr = reader.readLine()) != null) {
list.add(readStr);
}
reader.close();
if (reader == null) {
reader.close();
}
return list;
}
public Integer lineNumber() throws IOException {
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(path)));
lnr.skip(Long.MAX_VALUE);
Integer ite = lnr.getLineNumber();
return ite;
}
//执行创建、写入方法,覆盖原文件中文本
public void updateFile() throws IOException {
createFile();
writeFile(a);
}
//test main
public static void main(String[] args) {
String filepath = "test.csv";
String filepath1 = "test.txt";
String a = "111\n" +
"222\n" +
"333";
String ss=null;
//测试获取文件行数并输出
try {
FileUtil file = new FileUtil(filepath);
FileUtil file1 = new FileUtil(filepath1);
file.createFile();
int number = file1.lineNumber();
List<String> list = file1.readFile();
for (int i = 0; i <= number; i++) {
System.out.println(list.get(i));
ss=list.get(i);
file.writeFile(ss+"\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java-自定义文件工具类
最新推荐文章于 2024-04-12 20:30:02 发布