WritreDemo的使用: package com.tensent.readerAndwriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; public class WriterDemo { public static void main(String[] args) { File file = new File("d.txt"); Writer writer = null; try { writer = new FileWriter(file,false); writer.write(97); writer.write("www.baidu.com"); writer.write("河质院大呲花!"); writer.write(new char[]{'你','好','中','国','!'}); writer.flush(); } catch (IOException e) { e.printStackTrace(); }finally { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } }
CopyFileDemo的使用:
package com.tensent.inputdemo; import java.io.*; public class CopyFileDemo { public static void main(String[] args) { //创建数据源 File src = new File("F:\\14--Java容器2.pdf"); //创建目标数据源 File dest = new File("14--Java容器2.pdf"); FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { // 创建输入流对象 fileInputStream = new FileInputStream(src); //创建输出流对象 fileOutputStream = new FileOutputStream(dest); //定义一个缓冲区 byte[] buffer = new byte[1024]; int length = 0; //传输数据 while((length = fileInputStream.read(buffer))!=-1){ //输出到目标文件 fileOutputStream.write(buffer,0,length); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //当出现多个流对象的时候,根据创建流对象的顺序,倒序关闭流对象。 try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }