import java.io.*;public class TextFile { public String read(String fileName) { StringBuilder stringBuilder = new StringBuilder(); try { BufferedReader in = new BufferedReader(new FileReader( new File(fileName).getAbsoluteFile())); try { String string; while((string = in.readLine()) != null) { stringBuilder.append(string); stringBuilder.append("/n"); } } finally { in.close(); } } catch (IOException e) { throw new RuntimeException(); } return stringBuilder.toString(); } public void write(String fileName,String text) { try { PRintWriter out = new PrintWriter( new File(fileName).getAbsoluteFile()); try { out.print(text); } finally { out.close(); } } catch (IOException e) { throw new RuntimeException(); } } public void append(String fileName,String text) { try { PrintWriter out = new PrintWriter( new FileWriter(fileName,true)); try { out.println("/n" + text); } finally { out.close(); } } catch (IOException e) { throw new RuntimeException(); } } public void copy(String fileName1,String fileName2) { String text = this.read(fileName1); this.write(fileName2, text); } }4.wheel演示。
使用的時候通過:import 這個類導入進去然后創建一個該類的對象即可。測試代碼:import test.TextFile;public class testTextFile { public static void main(String[] args) { //測試讀取----------------------------- TextFile textFile = new TextFile(); String fileName = "F://file//測試文件.txt"; String string = textFile.read(fileName); System.out.print(string); //測試添加------------------------- textFile.append(fileName, "添加的內容"); String string2 = textFile.read(fileName); System.out.print(string2); //測試復制--------------------------- textFile.copy(fileName, "F://file//復制的文件.txt"); //測試寫入--------------------------- textFile.write("F://file//測試寫入.txt", "新寫入的內容(文件不存在)");//文件不存在 textFile.write(fileName, "新寫入的內容(文件存在)"); }}文件名:測試文件.txt。 路徑:F:/file/測試文件.txt 文件內容:測試TextFile。運行代碼之后,控制臺輸出內容:
這里是兩次讀取的內容。然后在目錄中,新出現了兩個文件,此時三個文件的內容分別如下:使用write時,創建的 測試寫入.txt。
使用copy時,復制過來的 復制的文件.txt
使用write時,將原來內容覆蓋掉后新的 測試文件.txt
新聞熱點
疑難解答