public class ReadWriteFile { public BufferedReader bufread; public BufferedWriter bufwriter; File writefile; String filepath, filecontent, read; String readStr = ""; // 從文本文件中讀取內容 public String read(String path) { try { filepath = path; // 得到文本文件的路徑 File file = new File(filepath); FileReader fileread = new FileReader(file); bufread = new BufferedReader(fileread); while ((read = bufread.readLine()) != null) { read = read + " /r/n "; readStr = readStr + read; } } catch (Exception d) { System.out.println(d.getMessage()); } return readStr; // 返回從文本文件中讀取內容 } // 向文本文件中寫入內容 public void write(String path, String content, boolean append) { try { boolean addStr = append; // 通過這個對象來判斷是否向文本文件中追加內容 filepath = path; // 得到文本文件的路徑 filecontent = content; // 需要寫入的內容 writefile = new File(filepath); if (writefile.exists() == false) // 如果文本文件不存在則創建它 { writefile.createNewFile(); writefile = new File(filepath); // 重新實例化 } FileWriter filewriter = new FileWriter(writefile, addStr); // 刪除原有文件的內容 java.io.RandomAccessFile file = new java.io.RandomAccessFile(path, " rw "); file.setLength(0); // 寫入新的文件內容 filewriter.write(filecontent); filewriter.close(); filewriter.flush(); } catch (Exception d) { System.out.println(d.getMessage()); } } public static void main(String[] args) throws Exception { ReadWriteFile rt = new ReadWriteFile(); String filecontent = rt.read(" c:/test.xml "); rt.write(" c:/test.xml ", filecontent, true); } }