List of usage examples for java.io BufferedInputStream close
public void close() throws IOException
From source file:org.dataconservancy.packaging.tool.impl.PackageStateSerializationIT.java
/** * Serializes the entire PackageState object to a zip file, then re-reads the zip file and initializes a fresh * PackageState object. The two state objects are compared for equality. * * @throws Exception/* w ww. j ava2 s .c om*/ */ @Test public void testSerializationRoundTrip() throws Exception { // Serialize the PackageState to a zip file. FileOutputStream out = new FileOutputStream(stateFile); underTest.serialize(state, out); out.close(); assertTrue(stateFile.exists() && stateFile.length() > 1); // Deserialize the PackageState from the zip. PackageState deserializedState = new PackageState(); BufferedInputStream in = new BufferedInputStream(new FileInputStream(stateFile)); underTest.deserialize(deserializedState, in); in.close(); // Verify the non-nullity of each @Serialize field in PackageState annotatedPackageStateFields.forEach((streamId, descriptor) -> { try { assertNotNull( "Expected non-null value for field " + descriptor.getName() + " on deserialized PackageState", descriptor.getReadMethod().invoke(deserializedState)); } catch (Exception e) { fail(e.getMessage()); } }); SerializeEqualsTester.serializeEquals(state, deserializedState); }
From source file:de.tudarmstadt.ukp.dkpro.core.io.mmax2.MMAXWriter.java
/** * Copies a source folder/file to a target folder/file. Used to duplicate the template project and template files. * @param source/* w ww . j a va 2 s .co m*/ * @param target * @throws IOException */ private void copy(File source, File target) throws IOException { if (source.isFile() && !target.exists()) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); int i; while ((i = in.read()) != -1) { out.write(i); } in.close(); out.close(); log.trace(target.getName() + " copied."); } if (source.isDirectory()) { target.mkdirs(); File[] files = source.listFiles(); for (File file : files) { if (!file.getName().endsWith(".svn")) { // do not copy svn files! copy(file, new File(target, file.getName())); } } } }
From source file:com.feilong.commons.core.io.FileUtil.java
/** * ?ByteArray./*from w w w . j a va 2 s . c om*/ * * @param file * file * @return byteArrayOutputStream.toByteArray(); * @throws UncheckedIOException * the unchecked io exception */ public static final byte[] convertFileToByteArray(File file) throws UncheckedIOException { InputStream inputStream = FileUtil.getFileInputStream(file); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] bytes = new byte[IOConstants.DEFAULT_BUFFER_LENGTH]; int j; try { while ((j = bufferedInputStream.read(bytes)) != -1) { byteArrayOutputStream.write(bytes, 0, j); } byteArrayOutputStream.flush(); return byteArrayOutputStream.toByteArray(); } catch (IOException e) { throw new UncheckedIOException(e); } finally { try { // ???StreamClose.??Close // finally Block??close() byteArrayOutputStream.close(); bufferedInputStream.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } }
From source file:com.cubusmail.gwtui.server.services.RetrieveAttachmentServlet.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WebApplicationContext context = WebApplicationContextUtils .getRequiredWebApplicationContext(request.getSession().getServletContext()); try {/*w ww . j av a 2s.c o m*/ String messageId = request.getParameter("messageId"); String attachmentIndex = request.getParameter("attachmentIndex"); boolean view = "1".equals(request.getParameter("view")); if (messageId != null) { IMailbox mailbox = SessionManager.get().getMailbox(); Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId)); List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg); int index = Integer.valueOf(attachmentIndex); MimePart retrievePart = attachmentList.get(index); ContentType contentType = new ContentType(retrievePart.getContentType()); String fileName = retrievePart.getFileName(); if (StringUtils.isEmpty(fileName)) { fileName = context.getMessage("message.unknown.attachment", null, SessionManager.get().getLocale()); } StringBuffer contentDisposition = new StringBuffer(); if (!view) { contentDisposition.append("attachment; filename=\""); contentDisposition.append(fileName).append("\""); } response.setHeader("cache-control", "no-store"); response.setHeader("pragma", "no-cache"); response.setIntHeader("max-age", 0); response.setIntHeader("expires", 0); if (!StringUtils.isEmpty(contentDisposition.toString())) { response.setHeader("Content-disposition", contentDisposition.toString()); } response.setContentType(contentType.getBaseType()); // response.setContentLength( // MessageUtils.calculateSizeFromPart( retrievePart ) ); BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream()); OutputStream outputStream = response.getOutputStream(); byte[] inBuf = new byte[1024]; int len = 0; int total = 0; while ((len = bufInputStream.read(inBuf)) > 0) { outputStream.write(inBuf, 0, len); total += len; } bufInputStream.close(); outputStream.flush(); outputStream.close(); } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } }
From source file:com.cubusmail.server.services.RetrieveAttachmentServlet.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WebApplicationContext context = WebApplicationContextUtils .getRequiredWebApplicationContext(request.getSession().getServletContext()); try {/*from www. j a v a 2 s . c o m*/ String messageId = request.getParameter("messageId"); String attachmentIndex = request.getParameter("attachmentIndex"); boolean view = "1".equals(request.getParameter("view")); if (messageId != null) { IMailbox mailbox = SessionManager.get().getMailbox(); Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId)); List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg); int index = Integer.valueOf(attachmentIndex); MimePart retrievePart = attachmentList.get(index); ContentType contentType = new ContentType(retrievePart.getContentType()); String fileName = retrievePart.getFileName(); if (StringUtils.isEmpty(fileName)) { fileName = context.getMessage("message.unknown.attachment", null, SessionManager.get().getLocale()); } StringBuffer contentDisposition = new StringBuffer(); if (!view) { contentDisposition.append("attachment; filename=\""); contentDisposition.append(fileName).append("\""); } response.setHeader("cache-control", "no-store"); response.setHeader("pragma", "no-cache"); response.setIntHeader("max-age", 0); response.setIntHeader("expires", 0); if (!StringUtils.isEmpty(contentDisposition.toString())) { response.setHeader("Content-disposition", contentDisposition.toString()); } response.setContentType(contentType.getBaseType()); // response.setContentLength( // MessageUtils.calculateSizeFromPart( retrievePart ) ); BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream()); OutputStream outputStream = response.getOutputStream(); byte[] inBuf = new byte[1024]; int len = 0; int total = 0; while ((len = bufInputStream.read(inBuf)) > 0) { outputStream.write(inBuf, 0, len); total += len; } bufInputStream.close(); outputStream.flush(); outputStream.close(); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } }
From source file:se.vgregion.services.calendar.CalendarServiceImpl.java
Calendar parseIcalUrl(String url) throws IOException, ParserException { BufferedInputStream bis = null; InputStream in = null;//w w w . j a va 2 s . c om try { bis = null; in = null; URL url2 = new URL(url); in = url2.openStream(); bis = new BufferedInputStream(in); CalendarBuilder builder = new CalendarBuilder(); return builder.build(bis); } finally { if (bis != null) { bis.close(); } if (in != null) { in.close(); } } }
From source file:org.dswarm.graph.gdm.test.BaseGDMResourceTest.java
protected void readGDMFromDB(final String recordClassURI, final String dataModelURI, final int numberOfStatements, final Optional<Integer> optionalAtMost) throws IOException { final ObjectMapper objectMapper = Util.getJSONObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); final ObjectNode requestJson = objectMapper.createObjectNode(); requestJson.put(DMPStatics.RECORD_CLASS_URI_IDENTIFIER, recordClassURI); requestJson.put(DMPStatics.DATA_MODEL_URI_IDENTIFIER, dataModelURI); if (optionalAtMost.isPresent()) { requestJson.put(DMPStatics.AT_MOST_IDENTIFIER, optionalAtMost.get()); }/*from w w w . j a va 2 s. c o m*/ final String requestJsonString = objectMapper.writeValueAsString(requestJson); // POST the request final ClientResponse response = target().path("/get").type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, requestJsonString); Assert.assertEquals("expected 200", 200, response.getStatus()); final InputStream actualResult = response.getEntity(InputStream.class); final BufferedInputStream bis = new BufferedInputStream(actualResult, 1024); final ModelParser modelParser = new ModelParser(bis); final org.dswarm.graph.json.Model model = new org.dswarm.graph.json.Model(); final Observable<Void> parseObservable = modelParser.parse().map(resource1 -> { model.addResource(resource1); return null; }); parseObservable.toBlocking().lastOrDefault(null); bis.close(); actualResult.close(); LOG.debug("read '{}' statements", model.size()); Assert.assertEquals("the number of statements should be " + numberOfStatements, numberOfStatements, model.size()); }
From source file:com.vtls.opensource.jhove.JHOVEDocumentFactory.java
/** * Get a JHOVE Document from a {@link URL} source * @param _uri a resource URL//from w ww . j av a 2s .c o m * @param _stream an input stream code * @return a JDOM Document * @throws IOException * @throws JDOMException */ public Document getDocument(InputStream _stream, String _uri) throws IOException, JDOMException { RepInfo representation = new RepInfo(_uri); File file = File.createTempFile("vtls-jhove-", ""); file.deleteOnExit(); BufferedOutputStream output_stream = new BufferedOutputStream(new FileOutputStream(file)); BufferedInputStream input_stream = new BufferedInputStream(_stream); int stream_byte; while ((stream_byte = input_stream.read()) != -1) { output_stream.write(stream_byte); } output_stream.flush(); output_stream.close(); input_stream.close(); representation.setSize(file.length()); representation.setLastModified(new Date()); populateRepresentation(representation, file); file.delete(); return getDocumentFromRepresentation(representation); }
From source file:org.mobisocial.corral.ContentCorral.java
public static Uri storeContent(Context context, Uri contentUri, String type) { File contentDir;//from w w w.j ava2 s .c o m if (type != null && (type.startsWith("image/") || type.startsWith("video/"))) { contentDir = new File(Environment.getExternalStorageDirectory(), PICTURE_SUBFOLDER); } else { contentDir = new File(Environment.getExternalStorageDirectory(), FILES_SUBFOLDER); } if (!contentDir.exists() && !contentDir.mkdirs()) { Log.e(TAG, "failed to create musubi corral directory"); return null; } int timestamp = (int) (System.currentTimeMillis() / 1000L); String ext = CorralDownloadClient.extensionForType(type); String fname = timestamp + "-" + contentUri.getLastPathSegment() + "." + ext; File copy = new File(contentDir, fname); FileOutputStream out = null; InputStream in = null; try { contentDir.mkdirs(); in = context.getContentResolver().openInputStream(contentUri); BufferedInputStream bin = new BufferedInputStream(in); byte[] buff = new byte[1024]; out = new FileOutputStream(copy); int r; while ((r = bin.read(buff)) > 0) { out.write(buff, 0, r); } bin.close(); return Uri.fromFile(copy); } catch (IOException e) { Log.w(TAG, "Error copying file", e); if (copy.exists()) { copy.delete(); } return null; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { Log.e(TAG, "failed to close handle on store corral content", e); } } }
From source file:com.commonsware.android.EMusicDownloader.SingleAlbum.java
private Bitmap getImageBitmap(String url) { Bitmap bm = null;//from w w w .j a v a 2s . c o m try { URL aURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) aURL.openConnection(); long ifs = 0; ifs = conn.getContentLength(); if (ifs == -1) { conn.disconnect(); conn = (HttpURLConnection) aURL.openConnection(); ifs = conn.getContentLength(); } vArtExists = false; if (ifs > 0) { conn.connect(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bm = BitmapFactory.decodeStream(bis); bis.close(); is.close(); vArtExists = true; //Log.d("EMD - ","art exists - Hurray!"); } else { Log.e("EMD - ", "art fail ifs 0 " + ifs + " " + url); } } catch (IOException e) { vArtExists = false; Log.e("EMD - ", "art fail"); } return bm; }