IO_Buffer 整合 public class Main { public static void main(String[] args) { /** * 复制一个文件 */ //获取要读的文件 copy(“/Users/dllo/Desktop/地址.txt”,"/Users/dllo/Desktop/新地址.txt"); } //将 一段代码提取成一个方法 选中代码段 + cmd+alt+m private static void copy(String s, String s1) { try { FileInputStream fis = new FileInputStream(s); FileOutputStream fos = new FileOutputStream(s1); byte[] bytes = new byte[1024]; int length = 0; while ((length = fis.read(bytes)) != -1) { fos.write(bytes,0,length); } fos.close(); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } BufferedReader BufferedWriter public class BufferTest { public static void main(String[] args) { /** * 字节流 主要应用的是FileInputStream FileOutputStream * * 字符流主要应用 FileReader FileWriter * BufferedReader BufferedWriter */ read("/Users/dllo/Desktop/地址"); write("/Users/dllo/Desktop/输出.txt"); } private static void write(String writePath) { try { FileWriter fileWriter = new FileWriter(writePath); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); System.out.println("请输入内容"); String content = new Scanner(System.in).nextLine(); bufferedWriter.write(content); // bufferedWriter.newLine(); bufferedWriter.append("署名:luke"); //!!!!!!! flush() 保证数据不丢失 bufferedWriter.flush(); //强制清除 bufferedWriter.close(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } private static void read(String readPath) { try { FileReader reader = new FileReader(readPath); BufferedReader bufferedReader = new BufferedReader(reader); String result = ""; //记录每行数据的内容 String line = ""; //readLine() 按行读取数据 while((line= bufferedReader.readLine())!=null){ result += line+' '; } System.out.println(result); bufferedReader.close(); reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } 整合 public class ReaderAndWriter { public static void main(String[] args) { copy(“/Users/dllo/Desktop/地址","/Users/dllo/Desktop/新地址.txt"); } private static void copy(String readPath,String writePath) { try { FileReader fileReader = new FileReader(readPath); BufferedReader bufferedReader = new BufferedReader(fileReader); FileWriter fileWriter = new FileWriter(writePath); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); String line = ""; while ((line = bufferedReader.readLine())!=null){ bufferedWriter.write(line); bufferedWriter.newLine(); bufferedWriter.flush(); } //循环里外都写flush() 保证数据不丢失 bufferedWriter.flush(); bufferedWriter.close(); bufferedReader.close(); fileWriter.close(); fileReader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }