public class Main { public static void main ( String [ ] args ) throws Exception { try { BufferedWriter out = new BufferedWriter ( new FileWriter ( " filename " ) ) ; out . write ( " aString1 \n " ) ; out . close ( ) ; out = new BufferedWriter ( new FileWriter ( " filename " , true ) ) ; out . write ( " aString2 " ) ; out . close ( ) ; BufferedReader in = new BufferedReader ( new FileReader ( " filename " ) ) ; String str ; while ( ( str = in . readLine ( ) ) != null ) { System . out . println ( str ) ; in . close ( ) ; catch ( IOException e ) { System . out . println ( " exception occoured " + e ) ;

以上代码运行输出结果为:

aString1 aString2

Java 实例 Java 实例

static void file_add(String str) throws Exception { //首先创建一个备份文件,并读取原文件写入备份数据 File c = new File("C:/Users/神和五律/Desktop/c.txt"); BufferedWriter c_w = new BufferedWriter(new FileWriter("C:/Users/神和五律/Desktop/c.txt")); BufferedReader a_r = new BufferedReader(new FileReader("C:/Users/神和五律/Desktop/a.txt")); String a_copy; while((a_copy=a_r.readLine())!=null) { c_w.write(a_copy); c_w.write("\n"); c_w.close(); //再用备份文件先写入原文件缓冲区 BufferedReader c_r = new BufferedReader(new FileReader("C:/Users/神和五律/Desktop/c.txt")); String c_str; BufferedWriter a_w = new BufferedWriter(new FileWriter("C:/Users/神和五律/Desktop/a.txt")); while((c_str=c_r.readLine())!=null) { a_w.write(c_str); a_w.write("\n"); //先不要写入,再把需要追加的参数数据写入缓冲区 a_w .write(str); //然后写入 a_w.close(); //最后删除备份文件(也可以保留),删除需要中止该文件的所有数据流,最好所有的都结束 a_r.close(); a_w.close(); c_r.close(); c_w.close(); c.delete(); public static void main(String[] args) throws Exception{ file_add("ababababababab"); }
神和五律