List of usage examples for java.io FileInputStream available
public int available() throws IOException
From source file:org.openmrs.util.OpenmrsUtil.java
/** * Return a byte array representation of the given file * /*from w w w . j a va 2 s . co m*/ * @param file * @return byte[] file contents * @throws IOException */ public static byte[] getFileAsBytes(File file) throws IOException { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); byte[] b = new byte[fileInputStream.available()]; fileInputStream.read(b); return b; } catch (Exception e) { log.error("Unable to get file as byte array", e); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException io) { log.warn("Couldn't close fileInputStream: " + io); } } } return null; }
From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java
public String saveImage(String path, String fileName, String userNum) { // TODO Auto-generated method stub File sourceFile = new File(path); if (!sourceFile.exists()) { Log.d("File", "Source File not copied"); return ""; } else {/*from w ww . j a va 2s . c o m*/ FileInputStream fileInputStream; double size = 0; try { fileInputStream = new FileInputStream(sourceFile); size = fileInputStream.available(); fileInputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } double fsize = FILE_SIZE_ERROR * 1024 * 1024; Log.d("size", size + " @"); Log.d("fsize", fsize + " @"); String fileuri = copyfile(fileName, userNum, sourceFile); Log.d("File", "Source File copied"); if (size > fsize) { return FILE_SIZE_ERROR + ""; } else { return fileuri; } } }
From source file:com.hollandhaptics.babyapp.BabyService.java
/** * @param sourceFile The file to upload. * @return int The server's response code. * @brief Uploads a file to the server. Is called by uploadAudioFiles(). */// ww w. j a v a 2s . c o m public int uploadFile(File sourceFile) { HttpURLConnection conn; DataOutputStream dos; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1024 * 1024; String sourceFileUri = sourceFile.getAbsolutePath(); if (!sourceFile.isFile()) { Log.e("uploadFile", "Source File does not exist :" + sourceFileUri); return 0; } else { try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("fileToUpload", sourceFileUri); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\";filename=\"" + sourceFileUri + "\"" + 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); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 200) { boolean deleted = sourceFile.delete(); Log.i("Deleted succes", String.valueOf(deleted)); } //close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); Log.e("Upload file to server", "Exception : " + e.getMessage(), e); } return serverResponseCode; } // End else block }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractConnectorController.java
private void loadConnectorJsp(Service service, HttpServletResponse response) { FileInputStream fileinputstream = null; String jspProvidedByService = connectorConfigurationManager.getJspPath(service); try {/* w w w.ja va 2s . com*/ if (StringUtils.isNotBlank(jspProvidedByService)) { String cssdkFilesDirectory = FilenameUtils.concat( config.getValue(Names.com_citrix_cpbm_portal_settings_services_datapath), service.getServiceName() + "_" + service.getVendorVersion()); String jspPath = cssdkFilesDirectory + "/" + CssdkConstants.JSP_DIRECTORY + "/" + jspProvidedByService; fileinputstream = new FileInputStream(jspPath); if (fileinputstream != null) { int numberBytes = fileinputstream.available(); byte bytearray[] = new byte[numberBytes]; fileinputstream.read(bytearray); response.setContentType("text/html"); OutputStream outputStream = response.getOutputStream(); response.setContentLength(numberBytes); outputStream.write(bytearray); outputStream.flush(); outputStream.close(); fileinputstream.close(); return; } } } catch (FileNotFoundException e) { logger.error("FileNot Found...", e); } catch (IOException e) { logger.error("IOException Found...", e); } response.setStatus(HttpServletResponse.SC_NOT_FOUND); }
From source file:poke.client.ClientConnection.java
public void docAdd(String nameSpace, String filePath) { Header.Builder docAddReqHeader = Header.newBuilder(); docAddReqHeader.setRoutingId(Routing.DOCADD); docAddReqHeader.setOriginator("Doc add test"); Request.Builder docAddReqBuilder = Request.newBuilder(); docAddReqBuilder.setHeader(docAddReqHeader); Payload.Builder docAddPLBuilder = Payload.newBuilder(); if (nameSpace != null && nameSpace.length() > 0) docAddPLBuilder.setSpace(NameSpace.newBuilder().setName(nameSpace).build()); String fileExt = FilenameUtils.getExtension(filePath); String fileName = FilenameUtils.getName(filePath); java.io.File file = FileUtils.getFile(filePath); long fileSize = FileUtils.sizeOf(file); logger.info("Size of the file to be sent " + fileSize); long totalChunk = ((fileSize / MAX_UNCHUNKED_FILE_SIZE)) + 1; if (fileSize < MAX_UNCHUNKED_FILE_SIZE) { logger.info(" DocADD: Sending the complete file in unchunked mode"); logger.info("Total number of chunks " + totalChunk); byte[] fileContents = null; try {//from w w w . ja v a2 s. c om fileContents = FileUtils.readFileToByteArray(file); } catch (IOException e) { logger.error("Error while reading the specified file " + e.getMessage()); return; } docAddPLBuilder.setDoc(Document.newBuilder().setDocName(fileName).setDocExtension(fileExt) .setChunkContent(ByteString.copyFrom(fileContents)).setDocSize(fileSize) .setTotalChunk(totalChunk).setChunkId(1)); docAddReqBuilder.setBody(docAddPLBuilder); try { // enqueue message outbound.put(docAddReqBuilder.build()); } catch (InterruptedException e) { logger.warn("Unable to deliver doc add message, queuing " + e.getMessage()); } } else { logger.info(" DocADD: Uploading the file in chunked mode"); logger.info("Total number of chunks " + totalChunk); try { int bytesRead = 0; int chunkId = 1; FileInputStream chunkeFIS = new FileInputStream(file); do { byte[] chunckContents = new byte[26214400]; bytesRead = IOUtils.read(chunkeFIS, chunckContents, 0, 26214400); logger.info("Total number of bytes read for chunk " + chunkId + ": " + bytesRead); // logger.info("Contents of the chunk "+chunkId+" : "+chunckContents); docAddPLBuilder.setDoc(Document.newBuilder().setDocName(fileName).setDocExtension(fileExt) .setChunkContent(ByteString.copyFrom(chunckContents)).setDocSize(fileSize) .setTotalChunk(totalChunk).setChunkId(chunkId)); docAddReqBuilder.setBody(docAddPLBuilder); try { outbound.put(docAddReqBuilder.build()); } catch (InterruptedException e) { logger.warn("Unable to deliver doc add (chunked) message, queuing " + e.getMessage()); } chunckContents = null; System.gc(); chunkId++; } while (chunkeFIS.available() > 0); logger.info("Out of chunked write while loop"); } catch (FileNotFoundException e) { logger.info("Requested File does not exists: File uploading Aborted " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { logger.info( "IO exception while uploading the requested file : File upload Aborted " + e.getMessage()); e.printStackTrace(); } } logger.info("DocAdd: File Send activity complete "); }
From source file:com.example.rartonne.appftur.HomeActivity.java
public int uploadFile(String sourceFileUri) { String fileName = sourceFileUri; HttpURLConnection conn = null; DataOutputStream dos = null;/*w w w. j a va 2 s .c o m*/ String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { //dialog.dismiss(); Log.e("uploadFile", "Source File not exist"); runOnUiThread(new Runnable() { public void run() { //messageText.setText("Source File not exist :"+uploadFilePath + "" + uploadFileName); } }); return 0; } else { try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + 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); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 200) { runOnUiThread(new Runnable() { public void run() { /*String msg = "File Upload Completed.\n\n See uploaded file here : \n\n" +" http://www.androidexample.com/media/uploads/" +uploadFileName;*/ //messageText.setText(msg); /*Toast.makeText(getApplicationContext(), "File Upload Complete.", Toast.LENGTH_SHORT).show();*/ } }); } //close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { //dialog.dismiss(); ex.printStackTrace(); runOnUiThread(new Runnable() { public void run() { //messageText.setText("MalformedURLException Exception : check script url."); /*Toast.makeText(getApplicationContext(), "MalformedURLException", Toast.LENGTH_SHORT).show();*/ } }); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { //dialog.dismiss(); e.printStackTrace(); runOnUiThread(new Runnable() { public void run() { //messageText.setText("Got Exception : see logcat "); /*Toast.makeText(getApplicationContext(), "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();*/ } }); Log.e("Upload file to server", "Exception : " + e.getMessage(), e); } // dialog.dismiss(); return serverResponseCode; } // End else block }
From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java
/** * ?/*from w ww. java 2 s . co m*/ * @param appWorkspace ? * @param source ? * @param target ?? * @param args JSONArray * @param callbackCtx nativejs * * args[2] fileKey ?name file? * args[3] fileName ??? image.jpg? * args[4] mimeType ?mimeimage/jpeg? * args[5] params HTTP????/ * args[6] trustEveryone * args[7] chunkedMode ??????true * @return FileUploadResult */ private XExtensionResult upload(String appWorkspace, String source, String target, JSONArray args, XCallbackContext callbackCtx) { XLog.d(CLASS_NAME, "upload " + source + " to " + target); HttpURLConnection conn = null; try { String fileKey = getArgument(args, 2, "file"); String fileName = getArgument(args, 3, "image.jpg"); String mimeType = getArgument(args, 4, "image/jpeg"); JSONObject params = args.optJSONObject(5); if (params == null) { params = new JSONObject(); } boolean trustEveryone = args.optBoolean(6); boolean chunkedMode = args.optBoolean(7) || args.isNull(7); JSONObject headers = args.optJSONObject(8); if (headers == null && params != null) { headers = params.optJSONObject("headers"); } String objectId = args.getString(9); //------------------ URL url = new URL(target); conn = getURLConnection(url, trustEveryone); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); setCookieProperty(conn, target); // ?? handleRequestHeader(headers, conn); byte[] extraBytes = extraBytesFromParams(params, fileKey); String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END; String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END; byte[] fileNameBytes = fileName.getBytes(ENCODING_TYPE); FileInputStream fileInputStream = (FileInputStream) getPathFromUri(appWorkspace, source); int maxBufferSize = XConstant.BUFFER_LEN; if (chunkedMode) { conn.setChunkedStreamingMode(maxBufferSize); } else { int stringLength = extraBytes.length + midParams.length() + tailParams.length() + fileNameBytes.length; XLog.d(CLASS_NAME, "String Length: " + stringLength); int fixedLength = (int) fileInputStream.getChannel().size() + stringLength; XLog.d(CLASS_NAME, "Content Length: " + fixedLength); conn.setFixedLengthStreamingMode(fixedLength); } // ??? OutputStream ouputStream = conn.getOutputStream(); DataOutputStream dos = new DataOutputStream(ouputStream); dos.write(extraBytes); dos.write(fileNameBytes); dos.writeBytes(midParams); XFileUploadResult result = new XFileUploadResult(); FileTransferProgress progress = new FileTransferProgress(); int bytesAvailable = fileInputStream.available(); int bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; int bytesRead = fileInputStream.read(buffer, 0, bufferSize); long totalBytes = 0; while (bytesRead > 0) { totalBytes += bytesRead; result.setBytesSent(totalBytes); dos.write(buffer, 0, bytesRead); bytesRead = fileInputStream.read(buffer, 0, bufferSize); if (objectId != null) { //?js??object ID? progress.setTotal(bytesAvailable); XLog.d(CLASS_NAME, "total=" + bytesAvailable); progress.setLoaded(totalBytes); progress.setLengthComputable(true); XExtensionResult progressResult = new XExtensionResult(XExtensionResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); callbackCtx.sendExtensionResult(progressResult); } synchronized (abortTriggered) { if (objectId != null && abortTriggered.contains(objectId)) { abortTriggered.remove(objectId); throw new AbortException(ABORT_EXCEPTION_UPLOAD_ABORTED); } } } dos.writeBytes(tailParams); fileInputStream.close(); dos.flush(); dos.close(); checkConnection(conn); setUploadResult(result, conn); // if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) { ((HttpsURLConnection) conn).setHostnameVerifier(mDefaultHostnameVerifier); HttpsURLConnection.setDefaultSSLSocketFactory(mDefaultSSLSocketFactory); } XLog.d(CLASS_NAME, "****** About to return a result from upload"); return new XExtensionResult(XExtensionResult.Status.OK, result.toJSONObject()); } catch (AbortException e) { JSONObject error = createFileTransferError(ABORTED_ERR, source, target, conn); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (MalformedURLException e) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error); } catch (JSONException e) { XLog.e(CLASS_NAME, e.getMessage()); return new XExtensionResult(XExtensionResult.Status.JSON_EXCEPTION); } catch (Throwable t) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error); } finally { if (conn != null) { conn.disconnect(); } } }
From source file:it.doqui.index.ecmengine.test.TestBackoffice.java
private byte[] getBinary(String cFile) throws Exception { FileInputStream fInput = new FileInputStream(cFile); byte[] aByte = new byte[fInput.available()]; fInput.read(aByte);/*from www . j a v a 2 s. c om*/ fInput.close(); return aByte; }
From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java
public int uploadFile(String sourceFileUri) { String upLoadServerUri = ""; upLoadServerUri = "http://ip.roaming4world.com/esstel/fetch_contacts_upload.php"; String fileName = sourceFileUri; Log.d("file upload url", upLoadServerUri); HttpURLConnection conn = null; DataOutputStream dos = null;/* w w w.j a v a2 s.c om*/ String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { Log.d("uploadFile", "Source File Does not exist"); return 0; } int serverResponseCode = 0; try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + selfNumber + "-" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size 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); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.d("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); //close the streams // fileInputStream.close(); dos.flush(); dos.close(); Log.d("Contact file ", "uploaded"); } catch (MalformedURLException ex) { ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); } return serverResponseCode; }