zoukankan      html  css  js  c++  java
  • Java IO 流-- 文件拷贝

    IO流操作套路:
    1、创建源;
    2、选择流;
    3、操作;
    4、释放资源
    上代码:

    package com.xzlf.io;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    /**
     * 文件拷贝
     * @author xzlf
     *
     */
    public class CopyFile {
    	public static void main(String[] args) {
    //		copy("src/com/xzlf/io/CopyFile.java", "src/CopyFile.txt");
    		copy("f:/aa/1.jpg", "src/1.jpg");
    
    	}
    
    	public static void copy(String srcPath, String destPath) {
    		// 1、创建源
    		File src = new File(srcPath);
    		File dest = new File(destPath);
    		// 2、选择流
    		InputStream is = null;
    		OutputStream os = null;
    		try {
    			is = new FileInputStream(src);
    			os = new FileOutputStream(dest);
    			byte[] flush = new byte[1024];
    			int len = -1;
    			// 3、操作(循环读取)
    			while ((len = is.read(flush)) != -1) {
    				os.write(flush, 0, len);
    			}
    			os.flush();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			// 4、释放资源
    			try {
    				if (os != null) {
    					os.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    			try {
    				if (is != null) {
    					is.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    }
    
    

    以上是IO的基本操作,IO的操作都可以按这样的套路来。

    重视基础,才能走的更远。
  • 相关阅读:
    mongo备份&恢复
    logstash参数配置
    elasticsearch索引自动清理
    Linux将公网ip映射到局域网ip
    普通用户创建ssh无密码访问
    软考介绍
    安装ffmpeg
    Hadoop实战-Flume之自定义Sink(十九)
    Hadoop实战-Flume之自定义Source(十八)
    Hadoop实战-Flume之Sink Load-balancing(十七)
  • 原文地址:https://www.cnblogs.com/xzlf/p/12681538.html
Copyright © 2011-2022 走看看