JAVA学习笔记0007----输入输出流

输入输出:InputStream & OutputStream

1、文件copy 和 照片的copy:

package com.dayuanit;

import java.io.IOException;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;

import java.util.Scanner;

public class Demo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.println("请输入你需要的文件名,格式如:copy F://x.txt F://y.txt");
        try {
            dominate(sc.nextLine());
        } catch(IOException io) {
            io.printStackTrace();
        }
        
        
    }
    
    public static void copy(String entry[]) throws IOException {
        File fountain = new File(entry[1]);
        File target = new File(entry[2]);
        
        InputStream input = new FileInputStream(fountain);
        byte[] buf = new byte[1024];
        int flag;
        String msg = "";
        while(-1 != (flag = input.read(buf))) {
            msg = new String(buf, 0, flag);
            System.out.println("文件的长度为:" + flag + "," + "\n" + "文件的内容为:" + msg);
        }
        
        OutputStream output = new FileOutputStream(target);
        output.write(msg.getBytes());
        output.flush();        
    }
    
    public static void dominate(String order) throws IOException {
        String entry[] = order.split(" ");
        if("copy" .equals(entry[0])) {
            copy(entry);
        }
        
        if("cat".equals(entry[0])) {
            reproduce(entry);
        }
        
    }
    
    public static void reproduce(String entry[]) throws IOException {
        File fountain = new File(entry[1]);
        File target = new File(entry[2]);
        
        InputStream fis= null;
        OutputStream fos = null;
        try {
            fis = new FileInputStream(fountain);
            fos = new FileOutputStream(target);
            byte[] buf = new byte[1024];
            int flag;
            while(-1 != (flag = fis.read(buf))) {
                fos.write(buf , 0, flag);
                System.out.println("文件的长度为:" + flag);
            }
        } catch(FileNotFoundException fn) {
            fn.getStackTrace();
        } catch(IOException io) {
            io.getStackTrace();
        } finally {
            if(null != fis) {
                fis.close();    
            }
             if(null != fos) {
                fos.close();
             }            
        }
        
    }
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值