`
wing123
  • 浏览: 790254 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

使用apache的IOUtils类完成文件下载(FileDownload)程序

    博客分类:
  • Java
阅读更多

 

package com.test;

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

import org.apache.commons.io.IOUtils;
import org.junit.BeforeClass;
import org.junit.Test;

public class FileItem {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @Test
    public void test() throws FileNotFoundException {
	// 模拟从服务器上下载文件
	String filename = "D:\\ufsoft\\nchome_huaxin\\modules\\hxsale\\file\\termb.lic";
	byte[] data = getFileByteArray(filename);
	if (null == data)
	    throw new FileNotFoundException("文件没有找到!");

	// 模拟写入本地磁盘
	String filename2 = "c:\\termb.lic";
	createNewFile(filename2, data);
    }

    /**
     * 写入本地磁盘
     * 
     * @param filename
     * @param data
     */
    private void createNewFile(String filename, byte[] data) {
	File file = new File(filename);
	OutputStream output = null;
	try {
	    if (!file.exists())
		file.createNewFile();
	    output = new FileOutputStream(file);
	    IOUtils.write(data, output);
	} catch (IOException e) {
	    e.printStackTrace();
	} finally {
	    if (null != output) {
		try {
		    output.close();
		} catch (IOException e1) {
		    e1.printStackTrace();
		}
		output = null;
	    }
	}

    }

    /**
     * 下载文件
     * 
     * @param filename
     * @return
     */
    private byte[] getFileByteArray(String filename) {
	File file = new File(filename);
	InputStream input = null;
	byte[] data = null;
	try {
	    if (!file.exists())
		return null;

	    input = new FileInputStream(file);
	    data = IOUtils.toByteArray(input);
	} catch (IOException e) {
	    e.printStackTrace();
	} finally {
	    if (null != input) {
		try {
		    input.close();
		} catch (IOException e1) {
		    e1.printStackTrace();
		}
		input = null;
	    }
	}
	return data;
    }

}

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics