黑马程序员-IO的复制

来源:互联网 发布:linux yum安装 lnmp 编辑:程序博客网 时间:2024/05/30 23:44

------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------

对于io流中很重的一个内容就是对文件的复制问题,今天我把这些复制程序的整理了一下:

复制一个文本

步骤:1,在D盘创建一个文件。用于存储C盘文件中的数据。2,定义读取流和C盘文件关联。3,通过不断的读写完成数据存储。4,关闭资源。*/import java.io.*;class CopyText {public static void main(String[] args) throws IOException{copy_2();}public static void copy_2(){FileWriter fw = null;FileReader fr = null;try{fw = new FileWriter("SystemDemo_copy.txt");fr = new FileReader("SystemDemo.java");char[] buf = new char[1024];int len = 0;while((len=fr.read(buf))!=-1){fw.write(buf,0,len);}}catch (IOException e){throw new RuntimeException("读写失败");}finally{if(fr!=null)try{fr.close();}catch (IOException e){}if(fw!=null)try{fw.close();}catch (IOException e){}}}}
复制一个图片

/*复制一个图片思路:1,用字节读取流对象和图片关联。2,用字节写入流对象创建一个图片文件。用于存储获取到的图片数据。3,通过循环读写,完成数据的存储。4,关闭资源。*/import java.io.*;class  CopyPic{public static void main(String[] args) {FileOutputStream fos = null;FileInputStream fis = null;try{fos = new FileOutputStream("c:\\2.jpg");fis = new FileInputStream("c:\\1.jpg");byte[] buf = new byte[1024];int len = 0;while((len=fis.read(buf))!=-1){fos.write(buf,0,len);}}catch (IOException e){throw new RuntimeException("复制文件失败");}finally{if(fis!=null)try{fis.close();}catch (IOException e){throw new RuntimeException("读取关闭失败");}if(fos!=null)try{fos.close();}catch (IOException e){throw new RuntimeException("写入关闭失败");}}}}

复制一个MP3

/*演示mp3的复制。通过缓冲区。BufferedOutputStreamBufferedInputStream*/import java.io.*;class CopyMp3{public static void main(String[] args) throws Exception{copy();}public static void copy() throws Exception{BufferedInputStream bis = new BufferedInputStream(new FileInputStream("d:\\1.mp3"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d:\\2.mp3"));int by = 0;while((by=bis.read())!=-1){bos.write(by);}bis.close();bos.close();}}

对于MP3的复印对于异常,我们还可以用try的方法来解决

*/import java.io.*;public class CopyMp3 {public static void main(String[] args) throws Exception {copy();}public static void copy() {BufferedInputStream bis = null;BufferedOutputStream bos = null;try {bis = new BufferedInputStream(new FileInputStream("d:\\1.mp3"));bos = new BufferedOutputStream(new FileOutputStream("d:\\2.mp3"));int by = 0;while ((by = bis.read()) != -1) {bos.write(by);}} catch (Exception e) {e.printStackTrace();} finally {if (bis != null) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}if (bos != null) {try {bos.close();} catch (IOException e) {e.printStackTrace();}}}}}


0 0