运用IO字节流实现文件的赋值粘贴

代码:

package com.bdqn;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class InputAndOutputDemo {
    public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream("hello.txt");
            fos = new FileOutputStream("helloCopy.txt");
            String str = "";
            int len = -1;
//            将获得的二进制数转为字符串
            while((len = fis.read())!=-1){
                str += (char)len;
            }
//            将字符串转为二进制byte数组
            byte[] bytes = str.getBytes();
//            将二进制byte数组写到新文件
            fos.write(bytes);
            System.out.println("复制文件完成!");
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            try {
                if(fos!=null) {
                    fos.close();
                }
                if(fis!=null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

运行结果:

将hello文件内容复制到helloCopy

 

posted @ 2019-03-06 16:46  杨文祥  阅读(290)  评论(0)    收藏  举报