用惯了python在使用java,在读取文件这真心觉得麻烦,写了一小段代码对java的读写进行了简单的封装,总算舒服了一点:
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; } }