java Remote File url How to Convert to Input Stream

  • 2021-11-29 07:24:17
  • OfStack

Directory java Remote File url Convert to Input Stream Obtain Input Stream According to URL Website Method 1 Method 2

java Remote File url Converted to Input Stream


URL url = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
// Set the timeout to 3 Seconds 
conn.setConnectTimeout(3*1000);
// Prevent the masking program from grabbing and returning 403 Errors 
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// Get the input stream 
InputStream inputStream = conn.getInputStream();

public static AjaxModel parseExcelForInfo(InputStream inputStream, String fileName, int taskId) {
    try {
        // Create workbook Object 
        Workbook workbook = null;
        if (fileName.contains(".xlsx")) {
            workbook = new XSSFWorkbook(inputStream);
        } else if (fileName.contains(".xls")) {
            workbook = new HSSFWorkbook(inputStream);
        } else {
            return AjaxModel.failed(-1, " Incorrect file type ");
        }
        // Get the 1 A sheet Table 
        Sheet sheetAt = workbook.getSheetAt(0);
        if (sheetAt != null) {
            // TODO  Calibration excel Head 
            Row headRow = sheetAt.getRow(0);
            for (int i = 0; i < BusinessSettlementConstants.TEMPLATE_COULMN.length; i++) {
                if (!FileUtil.getCellFormatValue(headRow.getCell(i)).trim().equals(BusinessSettlementConstants.TEMPLATE_COULMN[i])) {
                    LOGGER.info("parseExcelForInfo excel Incorrect order of header information, getCellFormatValue(headRow.getCell(i)):{}," +
                                    "BusinessSettlementConstants.TEMPLATE_COULMN[i]:{},taskId:{}", FileUtil.getCellFormatValue(headRow.getCell(i)),
                            BusinessSettlementConstants.TEMPLATE_COULMN[i], taskId);
                    return AjaxModel.failed("excel Incorrect header order :" + FileUtil.getCellFormatValue(headRow.getCell(i)));
                }
            }
            int startRowNum = sheetAt.getFirstRowNum() + 1;
            int lastRowNum = sheetAt.getLastRowNum();
 
            LOGGER.info(" Analyse excel Begin taskId:{} , from " {} "Line start , To the first " {} "End of line ", taskId, startRowNum, lastRowNum);
            List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
            for (int rowNum = startRowNum; rowNum <= lastRowNum; rowNum++) {
                //  Every 1 Row data 
                Row row = sheetAt.getRow(rowNum);
                Map<String, String> map = new HashMap<>();
                LOGGER.info("parseExcelForInfo row:{}", row);
                if (row != null && row.getCell(0) != null && StringUtils.isNotEmpty(row.getCell(0).getStringCellValue()) && row.getCell(2) != null && row.getCell(4) != null) {
                    LOGGER.info("parseExcelForInfo row:{},cell:{}", row, row.getCell(0));
                    //  Name 
                    map.put("userName", FileUtil.getCellFormatValue(row.getCell(0)));
                    
                    dataList.add(map);
                }
            }
            LOGGER.info("-------------- Parsing complete  dataList:{}", dataList);
            if (dataList.size() <= 0) {
                return AjaxModel.failed(-1, " Parsing table data is empty ");
            }
            AjaxModel success = AjaxModel.success();
            success.getData().put("dataList", dataList);
            return success;
        } else {
            LOGGER.info("sheet Content is empty ");
            return AjaxModel.failed(-1, " Table content is empty ");
        }
    } catch (Exception e) {
        LOGGER.error("parseExcelForInfo  Parsing exception ", e);
    }
    return AjaxModel.failed(-1, " Parsing table exception ");
}

public static String getCellFormatValue(Cell cell) {
    cell.setCellType(CellType.STRING);
    return cell.getStringCellValue();
}

Get the input stream according to the URL URL

Method 1


// File access path 
String url = "";
InputStream intstream = new URL(url).openStream();

Method 2


public InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), output);
            return new ByteArrayInputStream(output.toByteArray());
        } catch (Exception e) {
            logger.error("getInputStreamByUrl  Anomaly ,exception is {}", e);
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
            }
        }
        return null;
    }

Related articles: