outfox.dict.contest.util.FileUtils.java Source code

Java tutorial

Introduction

Here is the source code for outfox.dict.contest.util.FileUtils.java

Source

/**
 * @(#)FileUtils.java, 2015-12-9. 
 * 
 * Copyright 2015 Yodao, Inc. All rights reserved.
 * YODAO PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package outfox.dict.contest.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

import org.apache.http.HttpResponse;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import outfox.dict.contest.front.data.ContestConsts;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @author wangning
 *
 */
public class FileUtils {

    private static final Logger LOG = Logger.getLogger(FileUtils.class);

    /**
     * 
     * @param file
     * @return
     */
    public static byte[] getBytesFromFile(File file) {
        byte[] byteArray = null;
        try {
            if (file == null) {
                return null;
            }
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] b = new byte[4096];
            int n;
            while ((n = in.read(b)) != -1) {
                out.write(b, 0, n);
            }
            byteArray = out.toByteArray();
            in.close();
            out.close();
        } catch (IOException e) {
            LOG.error("FileUtils.getBytesFromFile error...", e);
        }
        return byteArray;
    }

    /**
     * 
     * @param b
     * @param outputFile
     * @return
     */
    public static File getFileFromBytes(byte[] b, String outputFile) {
        File file = null;
        BufferedOutputStream stream = null;
        try {

            file = new File(outputFile);
            FileOutputStream fstream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } catch (Exception e) {
            LOG.error("FileUtils.getFileFromBytes in catch error...", e);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    LOG.error("FileUtils.getFileFromBytes in finally error...", e);
                }
            }
        }
        return file;
    }

    /**
     * ??
     * @param downloadUrl
     * @return
     */
    public static byte[] getbytesFromURL(String downloadUrl) {
        HttpURLConnection httpUrl = null;
        ByteArrayOutputStream out = null;
        byte[] byteArray = null;
        InputStream in = null;
        try {
            // 
            URL url = new URL(downloadUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            // ?
            httpUrl.connect();
            // ??
            in = httpUrl.getInputStream();

            out = new ByteArrayOutputStream();
            byte[] b = new byte[4096];
            int n;
            while ((n = in.read(b)) != -1) {
                out.write(b, 0, n);
            }
            byteArray = out.toByteArray();
            in.close();
            out.close();
            httpUrl.disconnect();
        } catch (Exception e) {
            LOG.error("FileUtils.getBytesFromURL error...", e);
        }
        return byteArray;
    }

    /**
     * ?NOSurl
     * @param sourceUrl
     * @return
     */
    public static String uploadFile2Nos(String sourceUrl) {
        byte[] bytes = null;
        try {
            bytes = FileUtils.getbytesFromURL(sourceUrl);
        } catch (Exception e) {
            LOG.error("FileUtils.uploadFile2Nos(string) error...", e);
        }

        return uploadFile2Nos(bytes);
    }

    /**
     * ?NOSurl
     * tongkn
     * @param bytes
     * @return
     */
    public static String uploadFile2Nos(byte[] bytes, String fileName) throws Exception {
        if (bytes == null) {
            return null;
        }
        HttpResponse response = null;
        String result = null;
        try {
            //web ??
            String filedir = "tmpfile";
            File dir = new File(filedir);
            if (!dir.exists()) {
                dir.mkdir();
            }
            //            FileBody bin = new FileBody(FileUtils.getFileFromBytes(
            //                    bytes, filedir +"/file-"+ System.currentTimeMillis()+"-"+fileName));
            //ByteArrayBody
            ByteArrayBody bin = new ByteArrayBody(bytes, fileName);
            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("file", bin);
            reqEntity.addPart("video", new StringBody("false", Charset.forName("UTF-8")));
            //            reqEntity.addPart("contentType", new StringBody("audio/mpeg", Charset.forName("UTF-8")));
            response = HttpToolKit.getInstance().doPost(ContestConsts.NOS_UPLOAD_Interface, reqEntity);
            if (response != null) {
                String jsonString = EntityUtils.toString(response.getEntity());
                JSONObject json = JSON.parseObject(jsonString);
                if ("success".equals(json.getString("msg"))) {
                    return json.getString("url");
                }
            }
        } catch (Exception e) {
            LOG.error("FileUtils.uploadFile2Nos(bytes) error...", e);
            throw new Exception();
        } finally {
            HttpToolKit.closeQuiet(response);
        }
        return result;
    }

    /**
     * ?NOSurl
     * @param bytes
     * @return
     */
    public static String uploadFile2Nos(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        HttpResponse response = null;
        String result = null;
        try {
            FileBody bin = new FileBody(
                    FileUtils.getFileFromBytes(bytes, "tmpfile/file-" + System.currentTimeMillis()));
            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("file", bin);
            reqEntity.addPart("video", new StringBody("true", Charset.forName("UTF-8")));
            //            reqEntity.addPart("contentType", new StringBody("audio/mpeg", Charset.forName("UTF-8")));
            response = HttpToolKit.getInstance().doPost(ContestConsts.NOS_UPLOAD_Interface, reqEntity);
            if (response != null) {
                String jsonString = EntityUtils.toString(response.getEntity());
                JSONObject json = JSON.parseObject(jsonString);
                if ("success".equals(json.getString("msg"))) {
                    return json.getString("url");
                }
            }
        } catch (Exception e) {
            LOG.error("FileUtils.uploadFile2Nos(bytes) error...", e);
        } finally {
            HttpToolKit.closeQuiet(response);
        }
        return result;
    }
}