import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.time.LocalDate; import org.junit.Test; public class WriteDiary { /** * 字节流 复制文件内容 */ @Test public void test1() { FileInputStream fi = null; FileOutputStream fo = null; try { fi = new FileInputStream("G:\2222\1.txt"); fo = new FileOutputStream("G:\2222\2.txt"); int a; while ((a=fi.read())!=-1){/*这里的.read方法是把字 节一个接一个的传给a,当为空的时候则返回-1;*/ fo.write(a); } } catch (IOException e) { e.printStackTrace(); } finally { try { fi.close(); fo.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 字符流 复制文件内容 */ @Test public void test2() { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader("G:\2222\2.txt"); fw = new FileWriter("G:\2222\3.txt"); int a; while ((a=fr.read())!=-1){ fw.write(a); } } catch (IOException e) { e.printStackTrace(); } finally { try { fr.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 字符流 写日记 * @throws IOException */ @Test public void test3() throws IOException { //创建日期 LocalDate now = LocalDate.now(); StringBuffer content = new StringBuffer(""); File dir = new File("G:\2222\diary.txt"); if(dir.exists()) { //读取日记内容 InputStreamReader diary = new InputStreamReader(new FileInputStream("G:\2222\diary.txt")); BufferedReader buffer = new BufferedReader(diary); //有内容就读取 String line=""; while((line = buffer.readLine()) != null) { content.append(line); } //關閉IO流 buffer.close(); diary.close(); } //创建管道 InputStreamReader reader = new InputStreamReader(System.in); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("G:\2222\diary.txt")); BufferedReader in = new BufferedReader(reader); boolean flag = true; do { System.out.println("今天日期:" + now); content.append("日期:" + now); System.out.println("输入日记内容: "); content.append(" 日记内容:" + in.readLine()); System.out.println("输入作者: "); content.append(" 作者:" + in.readLine() + " "); System.out.println("是否繼續寫日記?(Y/N)"); //跳出循環 String choose = in.readLine(); if(choose.equals("N") || choose.equals("n")) { flag = false; writer.write(content.toString()); } } while (flag); //关闭IO流 reader.close(); writer.close(); in.close(); } }