用慣了python在使用java,在讀取檔案這真心覺得麻煩,寫了一小段代碼對java的讀寫進行了簡單的封裝,總算舒服了一點:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIml2ZuUWYxYmZhR2MiNjY3QGMjFGZlNTOzUWZjJGO2YzM1MWMfdWbp9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.gif)
package seleniumTest;
import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.util.List;
import java.util.ArrayList;
public class MyFile {
public File f;
public FileWriter fw;
public FileReader fr;
MyFile(String path){
f = new File(path);
if(f.exists() != true){
try{
f.createNewFile();
}catch(Exception e){
e.printStackTrace();
}
}
this.createWriter();
this.createReader();
}
private void createWriter(){
try {
fw = new FileWriter(f, true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void createReader(){
try {
fr = new FileReader(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FileWriter getWriter(){
return fw;
}
public BufferedReader getReader(){
BufferedReader br = new BufferedReader(fr);
return br;
}
public static void appendWriter(String path, List<String> lines){
MyFile tmp = new MyFile(path);
tmp.createWriter();
FileWriter fw = tmp.getWriter();
for(String line: lines){
try {
fw.write(String.format("%s%s", line.trim(), "\r\n"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static List<String> myReader(String path){
List<String> result = new ArrayList<String>();
MyFile tmp = new MyFile(path);
tmp.createWriter();
BufferedReader fr = tmp.getReader();
String s;
try {
while((s = fr.readLine()) != null){
result.add(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
View Code