博客转自:http://wing123.iteye.com/blog/765308
----------------------
- 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;
- }
- }