IO流简单来说就是输入流和输出流主要是用来处理设备之间的数据传输
案例1采用的是字节流方式,案例2采用字符流方式;字节流和字符流之间差异很大,读者需根据自己的场景使用
案例1:
采用字节流和包装流(读者可自行了解包装流,主要采用的是装饰器模式)的方式进行文件读写
public class FileCopy { public static void copyfile(File src,File res) throws Exception{ InputStream in=new BufferedInputStream(new FileInputStream(src)); OutputStream out=new BufferedOutputStream(new FileOutputStream(res)); byte[] bt=new byte[1024]; while(-1!=(in.read(bt))){ out.write(bt, 0, bt.length); } out.flush(); out.close(); in.close(); } public static void main(String[] args) { File src=new File("D:/tmp/test.xls"); File res=new File("D:/tmp/b.xls"); try { copyfile(src, res); } catch (Exception e) { e.printStackTrace(); } } }
案例2:
采用包装流和字符流进行文件读写
public class FileCopy { public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader( new InputStreamReader( new BufferedInputStream( new FileInputStream(new File("d:/tmp/a.txt"))),"GBK")); BufferedWriter out=new BufferedWriter( new OutputStreamWriter( new BufferedOutputStream( new FileOutputStream(new File("d:/tmp/b.txt"))),"GBK")); String line=null; while(null!=(line=br.readLine())){ out.write(line); out.newLine(); } out.flush(); out.close(); br.close(); } }