List of usage examples for java.io FileInputStream available
public int available() throws IOException
From source file:net.filterlogic.util.imaging.ToTIFF.java
/** * Load file into a byte array.//from www .ja v a 2 s . c o m * @param fileName * @return byte array */ public static byte[] loadFileToByteArray(String fileName) { FileInputStream fis; try { fis = new FileInputStream(fileName); int fisSize = fis.available(); byte[] in = new byte[fisSize]; // read entire file fis.read(in, 0, fisSize); fis.close(); return in; } catch (Exception fioe) { System.out.println(fioe.toString()); return null; } }
From source file:Main.java
@SuppressWarnings("resource") public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) { Logd(TAG, "Starting post..."); String html = ""; Boolean cont = true;//from w w w. jav a2 s .c om URL url = null; try { url = new URL(targetUrl); } catch (MalformedURLException e) { Log.e(TAG, "Invalid url: " + targetUrl); cont = false; throw new IllegalArgumentException("Invalid url: " + targetUrl); } if (cont) { if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) { HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER; HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); } else { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } } }; // Install the all-trusting trust manager SSLContext sc; try { sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } catch (NoSuchAlgorithmException e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); } catch (KeyManagementException e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); } } Logd(TAG, "Filename: " + file); Logd(TAG, "URL: " + targetUrl); HttpURLConnection connection = null; DataOutputStream outputStream = null; String pathToOurFile = file; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024; try { connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header) //connection.setChunkedStreamingMode(1024); // Enable POST method connection.setRequestMethod("POST"); setBasicAuthentication(connection, url); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); //outputStream.writeBytes(twoHyphens + boundary + lineEnd); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\"" + lineEnd + lineEnd); outputStream.write(param.getValue().getBytes("UTF-8")); outputStream.writeBytes(lineEnd); } String connstr = null; if (!file.equals("")) { FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); outputStream.writeBytes(twoHyphens + boundary + lineEnd); connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\"" + lineEnd; outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); Logd(TAG, "File length: " + bytesAvailable); try { while (bytesRead > 0) { try { outputStream.write(buffer, 0, bufferSize); } catch (OutOfMemoryError e) { e.printStackTrace(); html = "Error: outofmemoryerror"; return html; } bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } } catch (Exception e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); html = "Error: Unknown error"; return html; } outputStream.writeBytes(lineEnd); fileInputStream.close(); } else if (data != null) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd; outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = data.length; Logd(TAG, "File length: " + bytesAvailable); try { outputStream.write(data, 0, data.length); } catch (OutOfMemoryError e) { e.printStackTrace(); html = "Error: outofmemoryerror"; return html; } catch (Exception e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); html = "Error: Unknown error"; return html; } outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); Logd(TAG, "Server Response Code " + serverResponseCode); Logd(TAG, "Server Response Message: " + serverResponseMessage); if (serverResponseCode == 200) { InputStreamReader in = new InputStreamReader(connection.getInputStream()); BufferedReader br = new BufferedReader(in); String decodedString; while ((decodedString = br.readLine()) != null) { html += decodedString; } in.close(); } outputStream.flush(); outputStream.close(); outputStream = null; } catch (Exception ex) { // Exception handling html = "Error: Unknown error"; Logd(TAG, "Send file Exception: " + ex.getMessage()); } } if (html.startsWith("success:")) Logd(TAG, "Server returned: success:HIDDEN"); else Logd(TAG, "Server returned: " + html); return html; }
From source file:tv.phantombot.httpserver.HTTPServerCommon.java
/** * Method that handles files./*from w w w.jav a2s. c o m*/ * @param uriPath * @param exchange * @param hasPassword * @param needsPassword */ private static void handleFile(String uriPath, HttpExchange exchange, Boolean hasPassword, Boolean needsPassword) { if (needsPassword) { if (!hasPassword) { sendHTMLError(403, "Access Denied", exchange); return; } } File inputFile = new File("." + uriPath); if (inputFile.isDirectory()) { File[] fileList = inputFile.listFiles(); java.util.Arrays.sort(fileList); String outputString = ""; for (File file : fileList) { outputString += file.getName() + "\n"; } sendData("text/text", outputString, exchange); } else { try { FileInputStream fileStream = new FileInputStream(inputFile); byte[] outputBytes = new byte[fileStream.available()]; fileStream.read(outputBytes); sendData(inferContentType(uriPath), outputBytes, exchange); } catch (FileNotFoundException ex) { sendHTMLError(404, "Not Found", exchange); // The Alerts module will always query an MP3; do not print out a file missing error for this. if (!uriPath.endsWith(".mp3")) { com.gmt2001.Console.err.println("HTTP Server: handleFile(): " + ex.getMessage()); com.gmt2001.Console.err.logStackTrace(ex); } } catch (IOException ex) { sendHTMLError(500, "Server Error", exchange); com.gmt2001.Console.err.println("HTTP Server: handleFile(): " + ex.getMessage()); com.gmt2001.Console.err.logStackTrace(ex); } } }
From source file:tv.phantombot.httpserver.HTTPServerCommon.java
private static void handleRefresh(String uriPath, HttpExchange exchange, Boolean doMarquee, Boolean hasPassword, Boolean needsPassword, int marqueeWidth, int msgLength) { if (needsPassword) { if (!hasPassword) { sendHTMLError(403, "Access Denied", exchange); return; }// www . j a v a2 s.c om } File inputFile = new File("." + uriPath); if (inputFile.isDirectory()) { sendHTMLError(500, "Server Error: Refresh/Marquee does not support a directory, only a file", exchange); com.gmt2001.Console.err.println( "HTTP Server: handleFile(): Refresh/Marquee does not support a directory, only a file."); } else { try { FileInputStream fileStream = new FileInputStream(inputFile); byte[] fileRawData = new byte[fileStream.available()]; fileStream.read(fileRawData); String fileStringData = new String(fileRawData, StandardCharsets.UTF_8); String refreshString = ""; if (doMarquee) { refreshString = "<html><head><meta http-equiv=\"refresh\" content=\"5\" /><style>" + "body { margin: 5px; }" + ".marquee { " + " height: 25px;" + " width: " + marqueeWidth + "px;" + " overflow: hidden;" + " position: relative;" + "}" + ".marquee div {" + " display: block;" + " width: 200%;" + " height: 25px;" + " position: absolute;" + " overflow: hidden;" + " animation: marquee 5s linear infinite;" + "}" + ".marquee span {" + " float: left;" + " width: 50%;" + "}" + "@keyframes marquee {" + " 0% { left: 0; }" + " 100% { left: -100%; }" + "}" + "</style></head><body><div class=\"marquee\"><div>" + "<span>" + fileStringData.substring(0, Math.min(fileStringData.length(), msgLength)) + " </span>" + "<span>" + fileStringData.substring(0, Math.min(fileStringData.length(), msgLength)) + " </span>" + "</div></div></body></html>"; } else { refreshString = "<html><head><meta http-equiv=\"refresh\" content=\"5\" /></head>" + "<body>" + fileStringData + "</body></html>"; } sendData("text/html", refreshString, exchange); } catch (FileNotFoundException ex) { sendHTMLError(404, "Not Found", exchange); } catch (IOException ex) { sendHTMLError(500, "Server Error", exchange); com.gmt2001.Console.err.println("HTTP Server: handleFile(): " + ex.getMessage()); com.gmt2001.Console.err.logStackTrace(ex); } } }
From source file:org.openmrs.module.formentry.PublishInfoPath.java
private static String readFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); byte[] b = new byte[inputStream.available()]; inputStream.read(b);//from www . j a va2 s . c o m inputStream.close(); return new String(b); }
From source file:org.opentaps.common.event.PaginationEvents.java
/** * Download an existing Excel file from the ${opentaps_home}/runtime/output * directory. The Excel file is deleted after the download. * * @param filename the file name String object * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @return a <code>String</code> value *//*w w w .ja v a 2 s.co m*/ private static String downloadExcel(String filename, HttpServletRequest request, HttpServletResponse response) { File file = null; ServletOutputStream out = null; FileInputStream fileToDownload = null; try { out = response.getOutputStream(); file = new File(UtilCommon.getAbsoluteFilePath(request, filename)); fileToDownload = new FileInputStream(file); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=" + filename); response.setContentLength(fileToDownload.available()); int c; while ((c = fileToDownload.read()) != -1) { out.write(c); } out.flush(); } catch (FileNotFoundException e) { Debug.logError("Failed to open the file: " + filename, MODULE); return "error"; } catch (IOException ioe) { Debug.logError("IOException is thrown while trying to download the Excel file: " + ioe.getMessage(), MODULE); return "error"; } finally { try { out.close(); if (fileToDownload != null) { fileToDownload.close(); // Delete the file under /runtime/output/ this is optional file.delete(); } } catch (IOException ioe) { Debug.logError("IOException is thrown while trying to download the Excel file: " + ioe.getMessage(), MODULE); return "error"; } } return "success"; }
From source file:org.pentaho.di.job.entries.dostounix.JobEntryDosToUnix.java
private static int getFileType(FileObject file) throws Exception { int aCount = 0; // occurences of LF int dCount = 0; // occurences of CR FileInputStream in = null; try {/*from w ww. j a va 2 s .c o m*/ in = new FileInputStream(file.getName().getPathDecoded()); while (in.available() > 0) { int b = in.read(); if (b == CR) { dCount++; if (in.available() > 0) { b = in.read(); if (b == LF) { aCount++; } else { return TYPE_BINAY_FILE; } } } else if (b == LF) { aCount++; } } } finally { in.close(); } if (aCount == dCount) { return TYPE_DOS_FILE; } else { return TYPE_UNIX_FILE; } }
From source file:csic.ceab.movelab.beepath.Util.java
public static String readJSON(File file) { int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 64 * 1024; // old value 1024*1024 FileInputStream fileInputStream = null; String result = ""; try {//from w w w . j av a 2 s. c o m fileInputStream = new FileInputStream(file); 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) { bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } result = new String(buffer, "UTF-8"); } catch (FileNotFoundException e) { } catch (IOException e) { } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { } } } return result; }
From source file:com.haoqee.chatsdk.net.Utility.java
private static byte[] getFileByte(File file) { byte[] buffer = null; FileInputStream fin; try {/*from w w w . j av a 2 s.co m*/ fin = new FileInputStream(file.getPath()); int length; try { length = fin.available(); buffer = new byte[length]; fin.read(buffer); fin.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return buffer; }
From source file:MyClassLoader.java
public Class findClass(String name) { byte[] classData = null; try {/*from w ww . j a v a 2s . c o m*/ FileInputStream f = new FileInputStream("C:\\" + name + ".class"); int num = f.available(); classData = new byte[num]; f.read(classData); } catch (IOException e) { System.out.println(e); } Class x = defineClass(name, classData, 0, classData.length); return x; }