List of usage examples for java.io FileInputStream available
public int available() throws IOException
From source file:org.apache.drill.exec.client.DumpCat.java
/** * Querymode://from w ww.jav a2 s. c o m * $drill-dumpcat --file=local:///tmp/drilltrace/[queryid]_[tag]_[majorid]_[minor]_[operator] * Batches: 135 * Records: 53,214/53,214 // the first one is the selected records. The second number is the total number of records. * Selected Records: 53,214 * Average Record Size: 74 bytes * Total Data Size: 12,345 bytes * Number of Empty Batches: 1 * Schema changes: 1 * Schema change batch indices: 0 * @throws Exception */ protected void doQuery(FileInputStream input) throws Exception { int batchNum = 0; int emptyBatchNum = 0; BatchSchema prevSchema = null; List<Integer> schemaChangeIdx = Lists.newArrayList(); BatchMetaInfo aggBatchMetaInfo = new BatchMetaInfo(); while (input.available() > 0) { VectorAccessibleSerializable vcSerializable = new VectorAccessibleSerializable(DumpCat.allocator); vcSerializable.readFromStream(input); VectorContainer vectorContainer = (VectorContainer) vcSerializable.get(); aggBatchMetaInfo.add(getBatchMetaInfo(vcSerializable)); if (vectorContainer.getRecordCount() == 0) { emptyBatchNum++; } if (prevSchema != null && !vectorContainer.getSchema().equals(prevSchema)) schemaChangeIdx.add(batchNum); prevSchema = vectorContainer.getSchema(); batchNum++; vectorContainer.zeroVectors(); } /* output the summary stat */ System.out.println(String.format("Total # of batches: %d", batchNum)); //output: rows, selectedRows, avg rec size, total data size. System.out.println(aggBatchMetaInfo.toString()); System.out.println(String.format("Empty batch : %d", emptyBatchNum)); System.out.println(String.format("Schema changes : %d", schemaChangeIdx.size())); System.out.println(String.format("Schema change batch index : %s", schemaChangeIdx.toString())); }
From source file:report.ViewSearch.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); if (session != null && session.getAttribute("fieldsearch") != null) { Connection con = null;/*from ww w .jav a2s .c om*/ String url = "jdbc:postgresql://10.16.194.69:5432/ls"; String user = "test"; String password = "aerohive123!"; try { PreparedStatement pst = null; Class.forName("org.postgresql.Driver"); con = DriverManager.getConnection(url, user, password); //String reseller = "%"+request.getParameter("reseller")+"%"; StringBuffer sql = new StringBuffer(); if (session != null && session.getAttribute("sno") != null) { sql.append( "select ib.item AS \"SKU\",o.orderkey AS \"ENTITLEMENT KEY\",so_header.so_number AS \"SALES ORDER NUMBER\", so_header.po_check_number AS \"PO NUMBER\",so_header.reseller AS \"BILLING CUSTOMER\", "); } else { sql.append( "select so_item.item AS \"SKU\",so_item.entitlementkey AS \"ENTITLEMENT KEY\",so_item.quantity AS \"QUANTITY\",so_header.so_number AS \"SALES ORDER NUMBER\", so_header.po_check_number AS \"PO NUMBER\",so_header.reseller AS \"BILLING CUSTOMER\", "); } //sql.append("select so_item.item AS \"SKU\",so_item.entitlementkey AS \"ENTITLEMENT KEY\",so_item.quantity AS \"QUANTITY\",so_header.so_number AS \"SALES ORDER NUMBER\", so_header.po_check_number AS \"PO NUMBER\",so_header.reseller AS \"BILLING CUSTOMER\", "); sql.append( "so_header.end_user AS \"END USER\",so_header.ship_date AS \"SHIPPED DATE\",o.hmid AS \"HMID\", "); sql.append( " o.apnumber AS \"NUMBER OF HIVE OS DEVICES\", TO_CHAR(TO_TIMESTAMP(o.substartdate/1000), 'YYYY-MM-DD') AS \"LICENSE START DATE \",TO_CHAR(TO_TIMESTAMP(o.subenddate/1000), 'YYYY-MM-DD') AS \"LICENSE END DATE\", o.cvgnumber \"NUMBER OF CVG\", "); sql.append( "TO_CHAR(TO_TIMESTAMP(o.cvgsubstartdate/1000), 'YYYY-MM-DD') AS \"CVG SUBSCRIPTION START DATE\",TO_CHAR(TO_TIMESTAMP(o.cvgsubenddate/1000), 'YYYY-MM-DD') AS \"CVG SUBSCRIPTION END DATE\",o.vhmnumber AS \"VHM NUMBER\",o.evaluedays AS \"NUMBER OF DAYS\", "); sql.append( "TO_CHAR(TO_TIMESTAMP(o.startdate/1000), 'YYYY-MM-DD') AS \"SUPPORT START DATE\" , TO_CHAR(TO_TIMESTAMP(o.enddate/1000), 'YYYY-MM-DD') AS \"SUPPORT END DATE\" "); if (session != null && session.getAttribute("sno") != null) { sql.append( " from ns.so_header so_header inner join ns.temp_ib ib on substring(ib.salesordernumber from 14 for 100) =so_header.so_number "); sql.append(" inner join orderkey_information o on so_header.entitlement_key=o.orderkey "); } else { sql.append( " from ns.so_header so_header inner join ns.temp_so_item so_item on so_header.so_number=so_item.so_number"); sql.append(" inner join orderkey_information o on so_header.entitlement_key=o.orderkey "); } if (session != null && session.getAttribute("sno") != null) sql.append(" where ib.serialnumber='" + session.getAttribute("sno") + "' "); else if (session != null && session.getAttribute("so") != null) sql.append("where so_header.so_number='" + session.getAttribute("so") + "'"); else if (session != null && session.getAttribute("enduser") != null) sql.append("where so_header.end_user ILIKE '%" + session.getAttribute("enduser") + "%'"); else if (session != null && session.getAttribute("ek") != null) sql.append("where so_header.entitlement_key='" + session.getAttribute("ek") + "'"); if (session != null && session.getAttribute("reseller") != null) sql.append(" and so_header.reseller ILIKE ? order by o.orderkey"); if (session != null && session.getAttribute("sno") != null) sql.append(" LIMIT 1"); log.info("Field Search Extract Query :" + sql); pst = con.prepareStatement(sql.toString()); if (session != null && session.getAttribute("reseller") != null) pst.setString(1, (String) session.getAttribute("reseller")); ResultSet rs = pst.executeQuery(); FileWriter sw = new FileWriter("FieldSearchResults.csv"); CSVWriter writer = new CSVWriter(sw, '|'); writer.writeAll(rs, true); sw.close(); FileInputStream fis = new FileInputStream("FieldSearchResults.csv"); byte b[]; int x = fis.available(); b = new byte[x]; System.out.println(" b size" + b.length); fis.read(b); // FIXME: this is ugly if (response != null) { response.setContentType("application/ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=FieldSearchResults.csv"); } //response.setContentType(mimeType); OutputStream os = response.getOutputStream(); os.write(b); os.flush(); writer.flush(); writer.close(); fis.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } } else if (session != null && session.getAttribute("datesearch") != null) { Connection con = null; String url = "jdbc:postgresql://10.16.194.69:5432/ls"; String user = "test"; String password = "aerohive123!"; try { PreparedStatement pst = null; Class.forName("org.postgresql.Driver"); con = DriverManager.getConnection(url, user, password); //String reseller = "%"+request.getParameter("reseller")+"%"; StringBuffer sql = new StringBuffer(); sql.append( "select so_item.item AS \"SKU\",so_item.entitlementkey AS \"ENTITLEMENT KEY\",so_item.quantity AS \"QUANTITY\",so_header.so_number AS \"SALES ORDER NUMBER\", so_header.po_check_number AS \"PO NUMBER\",so_header.reseller AS \"BILLING CUSTOMER\", "); sql.append( "so_header.end_user AS \"END USER\",so_header.ship_date AS \"SHIPPED DATE\",o.hmid AS \"HMID\","); sql.append( " o.apnumber AS \"NUMBER OF HIVE OS DEVICES\", TO_CHAR(TO_TIMESTAMP(o.substartdate/1000), 'YYYY-MM-DD') AS \"LICENSE START DATE \",TO_CHAR(TO_TIMESTAMP(o.subenddate/1000), 'YYYY-MM-DD') AS \"LICENSE END DATE\", o.cvgnumber \"NUMBER OF CVG\" ,"); sql.append( "TO_CHAR(TO_TIMESTAMP(o.cvgsubstartdate/1000), 'YYYY-MM-DD') AS \"CVG SUBSCRIPTION START DATE\",TO_CHAR(TO_TIMESTAMP(o.cvgsubenddate/1000), 'YYYY-MM-DD') AS \"CVG SUBSCRIPTION END DATE\",o.vhmnumber AS \"VHM NUMBER\",o.evaluedays AS \"NUMBER OF DAYS\","); sql.append( "TO_CHAR(TO_TIMESTAMP(o.startdate/1000), 'YYYY-MM-DD') AS \"SUPPORT START DATE\" , TO_CHAR(TO_TIMESTAMP(o.enddate/1000), 'YYYY-MM-DD') AS \"SUPPORT END DATE\" "); sql.append( " from ns.so_header so_header inner join ns.temp_so_item so_item on so_header.so_number=so_item.so_number"); sql.append(" inner join orderkey_information o on so_header.entitlement_key=o.orderkey "); if (session.getAttribute("startdate") != null && session.getAttribute("enddate") != null) { sql.append("where so_header.date::DATE>='" + session.getAttribute("startdate") + "'"); sql.append("and so_header.date::DATE<='" + session.getAttribute("enddate") + "'"); } if (session.getAttribute("expdays") != null) { sql.append("where o.subenddate>='" + getDate(null) + "'"); sql.append("and o.subenddate<='" + getDate((String) session.getAttribute("expdays")) + "'"); } if (session != null && session.getAttribute("reseller") != null) sql.append(" and so_header.reseller ILIKE ? order by o.orderkey"); pst = con.prepareStatement(sql.toString()); if (session != null && session.getAttribute("reseller") != null) pst.setString(1, (String) session.getAttribute("reseller")); log.info("Search Date Extract Query :" + sql); ResultSet rs = pst.executeQuery(); FileWriter sw = new FileWriter("DateSearchResults.csv"); CSVWriter writer = new CSVWriter(sw, '|'); writer.writeAll(rs, true); sw.close(); FileInputStream fis = new FileInputStream("DateSearchResults.csv"); byte b[]; int x = fis.available(); b = new byte[x]; System.out.println(" b size" + b.length); fis.read(b); // FIXME: this is ugly if (response != null) { response.setContentType("application/ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=DateSearchResults.csv"); } //response.setContentType(mimeType); OutputStream os = response.getOutputStream(); os.write(b); os.flush(); writer.flush(); writer.close(); fis.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } } else { log.info("Search Field/Date Extract : Reseller Blank "); String nextJSP = "/login.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP); dispatcher.forward(request, response); } }
From source file:net.opentracker.android.OTSend.java
/** * Method used for uploading a file to a server; * /* w w w . java2s . c o m*/ * @param uploadServer * The server to upload the file to * @param internalPathName * The path to use taking the apps context into account * @param fileName * The file name to append to */ private static boolean uploadFile(String uploadServer, String internalPathName, String fileName) { LogWrapper.v(TAG, "uploadFile(uploadServer, pathName, fileName)"); String randomFileName = UUID.randomUUID() + ".gz"; try { // ------------------ CLIENT REQUEST FileInputStream fileInputStream = new FileInputStream(new File(internalPathName + fileName)); // Open a URL connection to the Servlet URL url = new URL(uploadServer); // Open a HTTP connection to the URLs conn = (HttpURLConnection) url.openConnection(); // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"upload\";" + " filename=\"" + randomFileName + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // close streams fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { LogWrapper.w(TAG, "From ServletCom CLIENT REQUEST: " + ex); return false; } catch (IOException ioe) { LogWrapper.w(TAG, "From ServletCom CLIENT REQUEST: " + ioe); return false; } // ------------------ read the SERVER RESPONSE try { inStream = new DataInputStream(conn.getInputStream()); String str; while ((str = inStream.readLine()) != null) { LogWrapper.v(TAG, "Server response: " + str); } inStream.close(); return true; } catch (IOException ioex) { LogWrapper.w(TAG, "Server response: " + ioex); return false; } }
From source file:com.sec.ose.osi.thread.job.identify.data.IdentifyErrorQueue.java
private void init(String userID) { identifyQueueErrorFileName = DAT_FILE_DIRECTORY + "/error_" + userID + ".dat"; File dir = new File(DAT_FILE_DIRECTORY); if (!dir.exists()) { if (dir.mkdirs() == false) { System.err.println("Can not create folder"); }/* w w w . j a v a 2 s. c om*/ } File file = new File(identifyQueueErrorFileName); FileInputStream fis = null; ObjectInputStream oisReader = null; try { if (!file.exists()) { file.createNewFile(); } else { fis = new FileInputStream(identifyQueueErrorFileName); if (fis != null && fis.available() > 0) { oisReader = new ObjectInputStream(fis); IdentifyData tmpIdentifiedData; while ((tmpIdentifiedData = (IdentifyData) oisReader.readObject()) != null) { log.debug("read from File : \n" + tmpIdentifiedData + "\n - queueSize: " + size()); identifyDataQueueError.add(tmpIdentifiedData); log.debug("add - queueSize: " + size()); } } } } catch (IOException e) { log.debug("The end of the stream/block data has been reached"); } catch (Exception e) { log.warn(e); } finally { try { if (oisReader != null) { try { oisReader.close(); } catch (Exception e) { log.debug(e); } } if (fis != null) { try { fis.close(); } catch (Exception e) { log.debug(e); } } } catch (Exception e) { log.warn(e); } } updateDatFileByIdentifyErrorQueue(); }
From source file:gov.nih.nci.ispy.web.taglib.CorrScatterPlotTag.java
public int doStartTag() { chart = null;// w w w . j a va 2 s . c om plotPoints.clear(); ServletRequest request = pageContext.getRequest(); HttpSession session = pageContext.getSession(); Object o = request.getAttribute(beanName); JspWriter out = pageContext.getOut(); ServletResponse response = pageContext.getResponse(); try { //retrieve the Finding from cache and build the list of PCAData points ISPYCorrelationFinding corrFinding = (ISPYCorrelationFinding) businessTierCache .getSessionFinding(session.getId(), taskId); Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>(); List<String> sampleIds = new ArrayList<String>(); List<DataPoint> points = corrFinding.getDataPoints(); ClinicalDataService cqs = ClinicalDataServiceFactory.getInstance(); IdMapperFileBasedService idMapper = IdMapperFileBasedService.getInstance(); List<ISPYPlotPoint> plotPoints = new ArrayList<ISPYPlotPoint>(); ISPYPlotPoint pp; SampleInfo si; ISPYclinicalDataQueryDTO dto; Set<String> sampleHolder = new HashSet<String>(); //set just holds one entry need this for the dto Set<PatientData> dataHolder = new HashSet<PatientData>(); PatientData pd = null; for (DataPoint p : points) { pp = new ISPYPlotPoint(p.getId()); pp.setX(p.getX()); pp.setY(p.getY()); pp.setZ(p.getZ()); String patientId = null; if (corrFinding.isSampleBased()) { si = idMapper.getSampleInfoForLabtrackId(p.getId()); if (si != null) { pp.setSampleInfo(si); patientId = si.getISPYId(); } else { logger.warn("Could not get sample info for DataPoint=" + p.getId()); } } else if (corrFinding.isPatientBased()) { patientId = p.getId(); } if (patientId != null) { dto = new ISPYclinicalDataQueryDTO(); sampleHolder.clear(); sampleHolder.add(patientId); dto.setRestrainingSamples(sampleHolder); dataHolder.clear(); dataHolder = cqs.getClinicalData(dto); if (dataHolder.size() == 1) { Iterator i = dataHolder.iterator(); pd = (PatientData) i.next(); pp.setPatientData(pd); } else { logger.error("Internal Error. Did not get back correct patient data for patientId=" + patientId); } } plotPoints.add(pp); } ISPYCorrelationScatterPlot plot = new ISPYCorrelationScatterPlot(plotPoints, corrFinding.getGroup1Name(), corrFinding.getGroup2Name(), corrFinding.getContinuousType1(), corrFinding.getContinuousType2(), corrFinding.getCorrelationValue(), ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase())); chart = plot.getChart(); ISPYImageFileHandler imageHandler = new ISPYImageFileHandler(session.getId(), "png", 650, 600); //The final complete path to be used by the webapplication String finalPath = imageHandler.getSessionTempFolder(); String finalURLpath = imageHandler.getFinalURLPath(); /* * Create the actual charts, writing it to the session temp folder */ ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); String mapName = imageHandler.createUniqueMapName(); //PrintWriter writer = new PrintWriter(new FileWriter(mapName)); ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 650, 600, info); //ImageMapUtil.writeBoundingRectImageMap(writer,"PCAimageMap",info,true); //writer.close(); /* This is here to put the thread into a loop while it waits for the * image to be available. It has an unsophisticated timer but at * least it is something to avoid an endless loop. **/ boolean imageReady = false; int timeout = 1000; FileInputStream inputStream = null; while (!imageReady) { timeout--; try { inputStream = new FileInputStream(finalPath); inputStream.available(); imageReady = true; inputStream.close(); } catch (IOException ioe) { imageReady = false; if (inputStream != null) { inputStream.close(); } } if (timeout <= 1) { break; } } out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName, true, info)); finalURLpath = finalURLpath.replace("\\", "/"); long randomness = System.currentTimeMillis(); //prevent image caching out.print("<img id=\"geneChart\" name=\"geneChart\" src=\"" + finalURLpath + "?" + randomness + "\" usemap=\"#" + mapName + "\" border=\"0\" />"); //(imageHandler.getImageTag(mapFileName)); } catch (IOException e) { logger.error(e); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); logger.error(sw.toString()); } catch (Throwable t) { logger.error(t); } return EVAL_BODY_INCLUDE; }
From source file:org.apache.pig.piggybank.test.storage.TestCSVExcelStorage.java
@Test public void storeCR() throws IOException { ArrayList<Tuple> inputTuples = new ArrayList<Tuple>(); inputTuples.add(Storage.tuple(1, "text", "a line\rand another line to write")); String expected = "1,text,\"a line\rand another line to write\"\n"; String expectedNoMultiline = "1,text,a line\rand another line to write\n"; // Prepare the input using mock.Storage() since this will not interpret \r Data data = Storage.resetData(pig); data.set("inputTuples", inputTuples); // Test for quoted when YES_MULTILINE // Execute/*from w w w . j a v a 2 s .c om*/ String testOut = dataDir + "csv_cr_quoted_output_yes_multiline"; String script = "A = load 'inputTuples' USING mock.Storage() as (f1:int, f2:chararray, f3:chararray);" + "STORE A INTO '" + testOut + "' USING " + "org.apache.pig.piggybank.storage.CSVExcelStorage(',', 'YES_MULTILINE', 'UNIX');"; Util.registerMultiLineQuery(pig, script); // Load result FileInputStream resultFile = new FileInputStream(testOut + "/part-m-00000"); byte[] actualBytes = new byte[resultFile.available()]; resultFile.read(actualBytes); resultFile.close(); String actual = new String(actualBytes); Assert.assertEquals(expected, actual); // Test for unquoted when NO_MULTILINE // Execute testOut = dataDir + "csv_cr_quoted_output_no_multiline"; script = "A = load 'inputTuples' USING mock.Storage() as (f1:int, f2:chararray, f3:chararray);" + "STORE A INTO '" + testOut + "' USING " + "org.apache.pig.piggybank.storage.CSVExcelStorage(',', 'NO_MULTILINE', 'UNIX');"; Util.registerMultiLineQuery(pig, script); // Load result resultFile = new FileInputStream(testOut + "/part-m-00000"); actualBytes = new byte[resultFile.available()]; resultFile.read(actualBytes); resultFile.close(); actual = new String(actualBytes); Assert.assertEquals(expectedNoMultiline, actual); }
From source file:com.example.android.bluetoothlegatt.BluetoothLeService.java
private String getStandardFile() { String sdcardPath = ""; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File sdCardDir = Environment.getExternalStorageDirectory();//?SDCard sdcardPath = sdCardDir.getPath(); }// w ww. ja v a 2 s .c om String standardFile = findFile(sdcardPath, "cardiochek_ble"); if (standardFile == null) { standardFile = findFile(sdcardPath + "/Downloads", "cardiochek_ble"); } if (standardFile == null) { Log.w(TAG, "no cardiochek_ble file"); return null; } try { File file = new File(standardFile); FileInputStream fis = new FileInputStream(file); int length = fis.available(); byte[] buffer = new byte[length]; fis.read(buffer); String res = EncodingUtils.getString(buffer, "UTF-8"); fis.close(); return res; } catch (Exception e) { Log.e(TAG, "read cardiochek_ble fail!"); } return null; }
From source file:com.axelor.apps.account.service.payment.PayboxService.java
/** Chargement de la cle AU FORMAT der * Utliser la commande suivante pour 'convertir' la cl 'pem' en 'der' * openssl rsa -inform PEM -in pubkey.pem -outform DER -pubin -out pubkey.der *//from w w w . j a v a2s . c om * @param pubKeyFile * @return * @throws Exception */ @Deprecated private PublicKey getPubKeyDer(String pubKeyPath) throws Exception { FileInputStream fis = new FileInputStream(pubKeyPath); DataInputStream dis = new DataInputStream(fis); byte[] pubKeyBytes = new byte[fis.available()]; dis.readFully(pubKeyBytes); fis.close(); dis.close(); KeyFactory keyFactory = KeyFactory.getInstance(this.ENCRYPTION_ALGORITHM); // extraction cle X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes); return keyFactory.generatePublic(pubSpec); }
From source file:com.baidu.rigel.biplatform.ma.file.serv.service.impl.LocalFileOperationServiceImpl.java
/** * {@inheritDoc}/*from w w w . j a v a 2 s . c o m*/ */ @Override public Map<String, Object> getFileAttributes(String filePath) { Map<String, Object> result = new HashMap<String, Object>(); if (StringUtils.isBlank(filePath)) { result.put(RESULT, FAIL); result.put(MSG, "??"); return result; } File file = new File(filePath); // ? if (!file.exists()) { result.put(RESULT, FAIL); result.put(MSG, "?"); return result; } // if (file.isDirectory()) { result.put(RESULT, SUCCESS); result.put("type", "directory"); return result; } FileInputStream inputStream = null; try { // ?? inputStream = new FileInputStream(file); result.put(RESULT, SUCCESS); result.put("type", "file"); result.put("size", new Integer(inputStream.available()).toString()); return result; } catch (IOException e) { result.put(RESULT, FAIL); result.put(MSG, "??"); return result; } finally { try { inputStream.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } }
From source file:org.bedework.util.security.pki.PKITools.java
private byte[] getKeys(final String fileName) throws PKIException { FileInputStream fstr = null; byte[] keys = null; try {//from w ww . j a v a 2s . co m fstr = new FileInputStream(fileName); keys = new byte[fstr.available()]; fstr.read(keys); } catch (Throwable t) { throw new PKIException(t); } finally { if (fstr != null) { try { fstr.close(); } catch (Throwable t) { } } } return keys; }