1. 程式人生 > >http文件導出寫文件

http文件導出寫文件

nag ppa 一個 adt hsi total 第一個 cati doc

jxl

<dependency>
			<groupId>net.sourceforge.jexcelapi</groupId>
			<artifactId>jxl</artifactId>
			<version>2.6.12</version>
		</dependency>

  ReadExcel

將xlsx 用excle打開另存為為xls

讀取excle

技術分享圖片
public class  ReadExcel{

    private String filePath;



    private
List<String[]> list = new ArrayList(); public ReadExcel(String filePath){ this.filePath = filePath; } public List<String[]> readExcel() throws IOException, BiffException{ //創建輸入流 InputStream stream = new FileInputStream(filePath); //獲取Excel文件對象
Workbook rwb = Workbook.getWorkbook(stream); //獲取文件的指定工作表 默認的第一個 Sheet sheet = rwb.getSheet(0); //行數(表頭的目錄不需要,從1開始) for(int i=0; i<sheet.getRows(); i++){ //創建一個數組 用來存儲每一列的值 String[] str = new String[sheet.getColumns()]; Cell cell
= null; //列數 for(int j=0; j<sheet.getColumns(); j++){ //獲取第i行,第j列的值 cell = sheet.getCell(j,i); str[j] = cell.getContents(); } //把剛獲取的列存入list list.add(str); } return list; } public void outData(){ for(int i=0;i<list.size();i++){ String[] str = (String[])list.get(i); for(int j=0;j<str.length;j++){ System.out.print(str[j]+‘\t‘); } System.out.println(); } } public static void main(String args[]) throws BiffException, IOException{ ReadExcel excel = new ReadExcel("C:\\Users\\hasee\\Documents\\263EM\\[email protected]\\receive_file\\aa.xls"); excel.readExcel(); excel.outData(); } }
View Code

FileOperation

寫文件

技術分享圖片
public class FileOperation {

    /**
     * 創建文件
     * @param fileName
     * @return
     */
    public static boolean createFile(File fileName)throws Exception{
        boolean flag=false;
        try{
            if(!fileName.exists()){
                fileName.createNewFile();
                flag=true;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 讀TXT文件內容
     * @param fileName
     * @return
     */
    public static String readTxtFile(File fileName)throws Exception{
        String result=null;
        FileReader fileReader=null;
        BufferedReader bufferedReader=null;
        try{
            fileReader=new FileReader(fileName);
            bufferedReader=new BufferedReader(fileReader);
            try{
                String read=null;
                while((read=bufferedReader.readLine())!=null){
                    result=result+read+"\r\n";
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(bufferedReader!=null){
                bufferedReader.close();
            }
            if(fileReader!=null){
                fileReader.close();
            }
        }
        System.out.println("讀取出來的文件內容是:"+"\r\n"+result);
        return result;
    }


    public static boolean writeTxtFile(String content,File  fileName)throws Exception{
        RandomAccessFile mm=null;
        boolean flag=false;
        FileOutputStream o=null;
        try {
            o = new FileOutputStream(fileName);
            o.write(content.getBytes("GBK"));
            o.close();
//   mm=new RandomAccessFile(fileName,"rw");
//   mm.writeBytes(content);
            flag=true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            if(mm!=null){
                mm.close();
            }
        }
        return flag;
    }



    public static void contentToTxt(String filePath, String content) {
        String str = new String(); //原有txt內容
        String s1 = new String();//內容更新
        try {
            File f = new File(filePath);
            if (f.exists()) {
                System.out.print("文件存在");
            } else {
                System.out.print("文件不存在");
                f.createNewFile();// 不存在則創建
            }
            BufferedReader input = new BufferedReader(new FileReader(f));

            while ((str = input.readLine()) != null) {
                s1 += str + "\n";
            }
            System.out.println(s1);
            input.close();
            s1 += content;

            BufferedWriter output = new BufferedWriter(new FileWriter(f));
            output.write(s1);
            output.close();
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

}
FileOperation

發請求

HttpClientUtil

技術分享圖片
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/spring-context.xml"})
public class HttpClientUtil {
    private String excelUrl = "C:\\Users\\hasee\\Documents\\263EM\\[email protected]\\receive_file\\aa.xls";
    @Autowired
    private IPpApiService ppApiService;
    @Autowired
    private IBaseRedisCacheService baseRedisCacheService;
    private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();


    private static final int TIMEOUT = 5 * 1000000;//5 * 1000

    //            StringUtils.strToInteger(propFactory.getConfig("max_http_connection"), 50);// 50
    private static final int MAX_HTTP_CONNECTION = 50;


    private static final int MAX_CONNECTION_PER_HOST = 10;// 10

    private static final String CHARSET_UTF8 = "UTF-8";

    private static HttpClientUtil instance = null;

    private static final String APP_KEY = "BOS";

    private static final String APP_SECRET = "WREW223421FDR134R";

    //  private static Logger logger = Logger.getLogger(HttpClientUtil.class);

    static {

        //HttpClient 連接池屬性設置,HOST並發數默認為50, 客戶端總並發數為200, TimeOut時間為5s.

        HttpConnectionManagerParams httpConnectionManagerParams = new HttpConnectionManagerParams();

        // 文檔參數說明:Sets the maximum number of connections allowed.
        httpConnectionManagerParams.setMaxTotalConnections(MAX_HTTP_CONNECTION);

        // 文檔參數說明: Sets the default maximum number of connections allowed for a given host config.
        httpConnectionManagerParams.setDefaultMaxConnectionsPerHost(MAX_CONNECTION_PER_HOST);

        // 讀取數據超時時間
        httpConnectionManagerParams.setSoTimeout(TIMEOUT);

        // 連接超時時間
        httpConnectionManagerParams.setConnectionTimeout(TIMEOUT);

        connectionManager.setParams(httpConnectionManagerParams);

    }

    public HttpClientUtil() {

    }

    public static HttpClientUtil getInstance() {

        if (null == instance) {

            synchronized (HttpClientUtil.class) {

                if (instance == null) {

                    instance = new HttpClientUtil();

                }

            }

        }

        return instance;

    }

    public HttpClient createHttpClient() {

        HttpClient httpClient = new HttpClient(connectionManager);

        return httpClient;

    }

    /**
     * 進行 http請求返回String結果
     *
     * @param url
     * @return
     */

    public String getHttpClientJson(String url) {

        HttpClient httpClient = createHttpClient();

        GetMethod getMethod = new GetMethod(url);

        try {

            httpClient.executeMethod(getMethod);

            InputStreamReader in = new InputStreamReader(getMethod.getResponseBodyAsStream(),
                    HttpClientUtil.CHARSET_UTF8);
            //            String jsonString = getMethod.getResponseBodyAsString();
            String jsonString = getStringByParams(in);

            return jsonString;

        } catch (Exception e) {
             /*   logger.error("Http Client GetMethod Execute is Exception , Message = " + e.getMessage(), e);*/
            return "{\"msg\":\"獲取賬戶余額信息失敗!\",\"success\":\"false\"}";
        } finally {
            if (getMethod != null)
                getMethod.releaseConnection();

        }

    }

    /**
     * 進行 http post請求返回String結果
     *
     * @param url
     * @return
     */

    public String postHttpClientJson(String url, String params) {

        HttpClient httpClient = createHttpClient();

        PostMethod postMethod = getPostMethod(url, params);

        try {
            //logger.info(" Request Navigate Url is : " + url);

            httpClient.executeMethod(postMethod);
            //            String jsonString = postMethod.getResponseBodyAsString();
            InputStreamReader in = new InputStreamReader(postMethod.getResponseBodyAsStream(),
                    HttpClientUtil.CHARSET_UTF8);
            String jsonString = getStringByParams(in);

            // 當地址端口錯誤時,返回為空,為防止Json解析異常
            if (jsonString == null || "".equals(jsonString)) {
                jsonString = "[{\"msg\":\"獲取折扣信息失敗!\",\"success\":\"false\"}]";
            }

            return jsonString;

        } catch (Exception e) {
            //  logger.error("Http Client PostMethod Execute is Exception , Message = " + e.getMessage(), e);
            return e.getMessage();
        } finally {
            if (postMethod != null)
                postMethod.releaseConnection();

        }

    }

    /**
     * @param params
     * @return List<NameValuePair>    返回類型
     * @throws
     * @Title: getCheckParam
     * @Description: (設置驗證參數)
     */
    private List<NameValuePair> getCheckParam(String params) {
        String digest = SecurityUtil.getDigest(params + APP_KEY + APP_SECRET);
        String timestamp = "" + new Date().getTime();
        final List<NameValuePair> nameValueList = new ArrayList<NameValuePair>();
        // 接口調用的請求格式
        nameValueList.add(new NameValuePair("params", params));

        nameValueList.add(new NameValuePair(Constants.DEFAULT_ALP_DIGEST_NAME, digest));
        nameValueList.add(new NameValuePair(Constants.DEFAULT_ALP_TIMESTAMP_NAME, timestamp));
        nameValueList.add(new NameValuePair("appkey", APP_KEY));

        return nameValueList;

    }

    /**
     * @param url
     * @param params
     * @return PostMethod    返回類型
     * @throws
     * @Title: getPostMethod
     * @Description: (設置params參數)
     */
    private PostMethod getPostMethod(String url, String params) {
        PostMethod postMethod = new PostMethod(url);

        List<NameValuePair> nameValueList = getCheckParam(params);

        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        postMethod.setRequestBody(nameValueList.toArray(new NameValuePair[nameValueList.size()]));
        //        postMethod.addRequestHeader("Connection", "close");

        return postMethod;

    }

    /**
     * @param in
     * @return String    返回類型
     * @throws IOException
     * @throws
     * @Title: getStringByParams
     * @Description: (將流文件轉換成字符)
     */
    private String getStringByParams(InputStreamReader in) throws IOException {

        BufferedReader reader = new BufferedReader(in);

        StringBuffer stringBuffer = new StringBuffer();

        String str = "";

        while ((str = reader.readLine()) != null) {

            stringBuffer.append(str);

        }

        String ts = stringBuffer.toString();

        return ts;
    }

    public String getParams(String siteCode) {

        StringBuilder str = new StringBuilder();
        str.append("{");
        str.append("\"siteCode\":\"" + siteCode + "\"");
        str.append("}");

        return str.toString();
    }

    @Test
    public void test0(){

    }

    @Test
    public void test() throws Exception {
        HttpClientUtil hcu = HttpClientUtil.getInstance();
        String url2 = "http://fo.ycgwl.com/rosefinch-web/ppapi/rest/queryFreightCount.api";
        List<DiscountOrPriceEntity> list = getList();

        StringBuilder sb = new StringBuilder();
        for (DiscountOrPriceEntity entity : list) {
            if (entity.getSendSiteCode() != null) {
                entity.setFromTime(new Date());
                String params = JSON.toJSONString(entity);

                String result2 = hcu.postHttpClientJson(url2, params);
                try {
                    DiscountOrPriceReturnEntity discountOrPriceReturnEntity = JSON.parseObject(result2, DiscountOrPriceReturnEntity.class);
                    sb.append(discountOrPriceReturnEntity.getPrice()+"\n");
                } catch (Exception ex) {
                    sb.append(result2+"\n");
                }
            } else {
                sb.append("發件網點或派件網點不存在"+"\n");
            }
        }
        FileOperation.writeTxtFile(sb.toString(), new File("C:\\Users\\hasee\\Documents\\263EM\\[email protected]\\receive_file\\aa.txt"));

    }
    @Test
    public void testOne(){
        HttpClientUtil hcu = HttpClientUtil.getInstance();
        String url2 = "http://fo.ycgwl.com/rosefinch-web/ppapi/rest/queryFreightCount.api";

        DiscountOrPriceEntity entity = new DiscountOrPriceEntity();
        entity.setSendSiteCode("TMS008");
        entity.setDispatchSiteCode("Z03419");
        entity.setCalcWeight(405.0);
        entity.setFromTime(new Date());

        String params = JSON.toJSONString(entity);

        String result2 = hcu.postHttpClientJson(url2, params);
        System.out.println(result2);
    }

    private List<DiscountOrPriceEntity> getList() throws IOException, BiffException {
        ReadExcel readExcel = new ReadExcel(excelUrl);
        final List<String[]> strings = readExcel.readExcel();

        List<DiscountOrPriceEntity> discountOrPriceEntities = new ArrayList<>();
        int i = 0;
        for (String[] ary : strings) {
            if (i == 0) {
                i++;
                continue;
            }
            i++;

           /* if (i ==100) {
                return discountOrPriceEntities;
            }*/
            DiscountOrPriceEntity entity = new DiscountOrPriceEntity();
            String sendSite = ary[2];
            String destination = ary[4];
            Double weight = Double.parseDouble(ary[9]);


            if (StringUtils.isNotEmpty(sendSite)) {
                BaseSiteEntity baseSiteEntityNameFromCache = this.baseRedisCacheService.getBaseSiteEntityNameFromCache(sendSite);
                if (baseSiteEntityNameFromCache == null) {
                    entity.setSendSiteCode(null);
                } else {
                    entity.setSendSiteCode(baseSiteEntityNameFromCache.getSiteCode());
                }
            } else {
                entity.setSendSiteCode(null);
            }
            if (StringUtils.isNotEmpty(destination)) {
                BaseSiteEntity baseSiteEntityNameFromCache1 = this.baseRedisCacheService.getBaseSiteEntityNameFromCache(destination);
                if (baseSiteEntityNameFromCache1 == null) {
                    entity.setSendSiteCode(null);
                } else {
                    entity.setDispatchSiteCode(baseSiteEntityNameFromCache1.getSiteCode());
                }
            } else {
                entity.setSendSiteCode(null);
            }

            entity.setCalcWeight(weight);
            discountOrPriceEntities.add(entity);
            System.out.println("拼裝完成"+i+"個");
        }
        return discountOrPriceEntities;
    }
}
HttpClientUtil

http文件導出寫文件