List of usage examples for java.io BufferedOutputStream flush
@Override public synchronized void flush() throws IOException
From source file:edu.stanford.epad.common.util.EPADFileUtils.java
/** * Unzip the specified file.//w w w .ja va2s. co m * * @param zipFilePath String path to zip file. * @throws IOException during zip or read process. */ public static void extractFolder(String zipFilePath) throws IOException { ZipFile zipFile = null; try { int BUFFER = 2048; File file = new File(zipFilePath); zipFile = new ZipFile(file); String newPath = zipFilePath.substring(0, zipFilePath.length() - 4); makeDirs(new File(newPath)); Enumeration<?> zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(newPath, currentEntry); File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed makeDirs(destinationParent); InputStream is = null; BufferedInputStream bis = null; FileOutputStream fos = null; BufferedOutputStream bos = null; try { if (destFile.exists() && destFile.isDirectory()) continue; if (!entry.isDirectory()) { int currentByte; byte data[] = new byte[BUFFER]; is = zipFile.getInputStream(entry); bis = new BufferedInputStream(is); fos = new FileOutputStream(destFile); bos = new BufferedOutputStream(fos, BUFFER); while ((currentByte = bis.read(data, 0, BUFFER)) != -1) { bos.write(data, 0, currentByte); } bos.flush(); } } finally { IOUtils.closeQuietly(bis); IOUtils.closeQuietly(is); IOUtils.closeQuietly(bos); IOUtils.closeQuietly(fos); } if (currentEntry.endsWith(".zip")) { extractFolder(destFile.getAbsolutePath()); } } } catch (Exception e) { log.warning("Failed to unzip: " + zipFilePath, e); throw new IllegalStateException(e); } finally { if (zipFile != null) zipFile.close(); } }
From source file:net.sf.sveditor.core.tests.utils.BundleUtils.java
public void unpackBundleTgzToFS(String bundle_path, File fs_path) { URL url = fBundle.getEntry(bundle_path); TestCase.assertNotNull(url);/*from ww w . ja v a 2s . c o m*/ if (!fs_path.isDirectory()) { TestCase.assertTrue(fs_path.mkdirs()); } InputStream in = null; GzipCompressorInputStream gz_stream = null; TarArchiveInputStream tar_stream = null; try { in = url.openStream(); } catch (IOException e) { TestCase.fail("Failed to open data file " + bundle_path + " : " + e.getMessage()); } try { gz_stream = new GzipCompressorInputStream(in); } catch (IOException e) { TestCase.fail("Failed to uncompress data file " + bundle_path + " : " + e.getMessage()); } tar_stream = new TarArchiveInputStream(gz_stream); try { byte tmp[] = new byte[4 * 1024]; int cnt; ArchiveEntry te; while ((te = tar_stream.getNextEntry()) != null) { // System.out.println("Entry: \"" + ze.getName() + "\""); File entry_f = new File(fs_path, te.getName()); if (te.getName().endsWith("/")) { // Directory continue; } if (!entry_f.getParentFile().exists()) { TestCase.assertTrue(entry_f.getParentFile().mkdirs()); } FileOutputStream fos = new FileOutputStream(entry_f); BufferedOutputStream bos = new BufferedOutputStream(fos, tmp.length); while ((cnt = tar_stream.read(tmp, 0, tmp.length)) > 0) { bos.write(tmp, 0, cnt); } bos.flush(); bos.close(); fos.close(); // tar_stream.closeEntry(); } tar_stream.close(); } catch (IOException e) { e.printStackTrace(); TestCase.fail("Failed to unpack tar file: " + e.getMessage()); } }
From source file:de.bps.onyx.plugin.OnyxExportManager.java
/** * Method exports the result.xmls of the given ResultSets in a zip file. * @param resultSets The resultsets to export. * @param exportDir The directory to store the zip file. * @param test The inputstream from referenced test resource (zip archived). * @param currentCourseNode current course node * @param sign sign the zip file// ww w . j a v a2 s . com * @return The filename of the exported zip file. */ public String exportAssessmentResults(List<QTIResultSet> resultSets, File exportDir, MediaResource test, CourseNode currentCourseNode, boolean sign, File csvFile) { String filename = createTargetFilename(currentCourseNode.getShortTitle(), "TEST"); if (!exportDir.exists()) { exportDir.mkdir(); } File archiveDir = new File(exportDir, filename + "__TMP/"); if (!archiveDir.exists()) { archiveDir.mkdir(); } // copy test File testFile = new File(archiveDir.getAbsolutePath() + File.separator + "qtitest.zip"); BufferedOutputStream target = null; try { target = new BufferedOutputStream(new FileOutputStream(testFile)); FileUtils.copy(test.getInputStream(), target, test.getSize()); target.flush(); } catch (FileNotFoundException e) { // do nothing } catch (IOException e) { e.printStackTrace(); } finally { if (target != null) { try { target.close(); } catch (IOException e) { } } } if (csvFile != null) { FileUtils.copyFileToDir(csvFile, archiveDir, ""); } File archiveName = new File(exportDir, filename); File fUserdataRoot = new File(WebappHelper.getUserDataRoot()); String pattern = "yyyy_MMM_dd__HH_mm_SSS"; SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); for (QTIResultSet rs : resultSets) { String username = rs.getIdentity().getName(); String resultXml = getResultXml(username, currentCourseNode.getModuleConfiguration().get(IQEditController.CONFIG_KEY_TYPE).toString(), currentCourseNode.getIdent(), rs.getAssessmentID()); File xml = new File(fUserdataRoot, resultXml); String userFilePart = filename + "__TMP/" + username + "_" + dateFormat.format(rs.getCreationDate()); if (xml != null && xml.exists()) { File file_s = new File(exportDir, userFilePart + ".xml"); //xml.copyTo(file_s); FileUtils.copyFileToFile(xml, file_s, false); } String summaryPDF = getResultSummaryPDF(username, currentCourseNode.getModuleConfiguration().get(IQEditController.CONFIG_KEY_TYPE).toString(), currentCourseNode.getIdent(), rs.getAssessmentID()); File pdf = new File(fUserdataRoot, summaryPDF); if (pdf != null && pdf.exists()) { File file_s = new File(exportDir, userFilePart + ".pdf"); //xml.copyTo(file_s); FileUtils.copyFileToFile(pdf, file_s, false); } String summaryHTML = getResultSummaryHTML(username, currentCourseNode.getModuleConfiguration().get(IQEditController.CONFIG_KEY_TYPE).toString(), currentCourseNode.getIdent(), rs.getAssessmentID()); File html = new File(fUserdataRoot, summaryHTML); if (html != null && html.exists()) { File file_s = new File(exportDir, userFilePart + ".html"); //xml.copyTo(file_s); FileUtils.copyFileToFile(html, file_s, false); } String resultZip = getResultZIP(username, currentCourseNode.getModuleConfiguration().get(IQEditController.CONFIG_KEY_TYPE).toString(), currentCourseNode.getIdent(), rs.getAssessmentID()); File zip = new File(fUserdataRoot, resultZip); if (zip != null && zip.exists()) { File file_s = new File(exportDir, userFilePart + ".zip"); //xml.copyTo(file_s); FileUtils.copyFileToFile(zip, file_s, false); } else { log.debug("no zip-results found at : " + (zip != null ? zip.getAbsolutePath() : " NULL")); } } boolean success = ZipUtil.zipAll(archiveDir, archiveName); if (success) { for (File file : archiveDir.listFiles()) { file.delete(); } archiveDir.delete(); } return filename; }
From source file:au.org.ala.layers.util.BatchConsumer.java
@Override public void run() { boolean repeat = true; String id = ""; while (repeat) { String currentBatch = null; try {/*from w w w . j a v a 2s . c o m*/ currentBatch = waitingBatchDirs.take(); id = new File(currentBatch).getName(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy hh:mm:ss:SSS"); String str = sdf.format(new Date()); BatchProducer.logUpdateEntry(id, "started", "started", str, null); writeToFile(currentBatch + "status.txt", "started at " + str, true); writeToFile(currentBatch + "started.txt", str, true); String fids = readFile(currentBatch + "fids.txt"); String points = readFile(currentBatch + "points.txt"); String gridcache = readFile(currentBatch + "gridcache.txt"); ArrayList<String> sample = null; HashMap[] pointSamples = null; if ("1".equals(gridcache)) { pointSamples = layerIntersectDao.sampling(points, 1); } else if ("2".equals(gridcache)) { pointSamples = layerIntersectDao.sampling(points, 2); } else { IntersectCallback callback = new ConsumerCallback(id); sample = layerIntersectDao.sampling(fids.split(","), splitStringToDoublesArray(points, ','), callback); } //convert pointSamples to string array if (pointSamples != null) { Set columns = new LinkedHashSet(); for (int i = 0; i < pointSamples.length; i++) { columns.addAll(pointSamples[i].keySet()); } //fids fids = ""; for (Object o : columns) { if (!fids.isEmpty()) { fids += ","; } fids += o; } //columns ArrayList<StringBuilder> sb = new ArrayList<StringBuilder>(); for (int i = 0; i < columns.size(); i++) { sb.add(new StringBuilder()); } for (int i = 0; i < pointSamples.length; i++) { int pos = 0; for (Object o : columns) { sb.get(pos).append("\n").append(pointSamples[i].get(o)); pos++; } } //format sample = new ArrayList<String>(); for (int i = 0; i < sb.size(); i++) { sample.add(sb.get(i).toString()); } } System.out.println("start csv output at " + sdf.format(new Date())); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(currentBatch + "sample.csv")); IntersectUtil.writeSampleToStream(splitString(fids, ','), splitString(points, ','), sample, bos); bos.flush(); bos.close(); System.out.println("finish csv output at " + sdf.format(new Date())); str = sdf.format(new Date()); BatchProducer.logUpdateEntry(id, "finished", "finished", str, fids.split(",").length + 1); writeToFile(currentBatch + "status.txt", "finished at " + str, true); writeToFile(currentBatch + "finished.txt", str, true); } catch (InterruptedException e) { //thread stop request repeat = false; break; } catch (Exception e) { if (currentBatch != null) { try { BatchProducer.logUpdateEntry(id, "error", "error", e.getMessage(), null); writeToFile(currentBatch + "status.txt", "error " + e.getMessage(), true); writeToFile(currentBatch + "error.txt", e.getMessage(), true); } catch (Exception ex) { ex.printStackTrace(); } } e.printStackTrace(); } currentBatch = null; } }
From source file:mamo.vanillaVotifier.JsonConfig.java
@Override public synchronized void load() throws IOException, InvalidKeySpecException { if (!configFile.exists()) { BufferedInputStream in = new BufferedInputStream(JsonConfig.class.getResourceAsStream("config.json")); StringBuilder stringBuilder = new StringBuilder(); int i;//from ww w. ja v a 2 s.co m while ((i = in.read()) != -1) { stringBuilder.append((char) i); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(configFile)); for (char c : stringBuilder.toString() .replaceAll("\\u000D\\u000A|[\\u000A\\u000B\\u000C\\u000D\\u0085\\u2028\\u2029]", System.getProperty("line.separator")) .toCharArray()) { out.write((int) c); } out.flush(); out.close(); } BufferedInputStream in = new BufferedInputStream(JsonConfig.class.getResourceAsStream("config.json")); JSONObject defaultConfig = new JSONObject(new JSONTokener(in)); in.close(); JSONObject config = new JSONObject( new JSONTokener(new BufferedInputStream(new FileInputStream(configFile)))); boolean save = JsonUtils.merge(defaultConfig, config); configVersion = config.getInt("config-version"); if (configVersion == 2) { v2ToV3(config); configVersion = 3; save = true; } logFile = new File(config.getString("log-file")); inetSocketAddress = new InetSocketAddress(config.getString("ip"), config.getInt("port")); publicKeyFile = new File(config.getJSONObject("key-pair-files").getString("public")); privateKeyFile = new File(config.getJSONObject("key-pair-files").getString("private")); if (!publicKeyFile.exists() && !privateKeyFile.exists()) { KeyPair keyPair = RsaUtils.genKeyPair(); PemWriter publicPemWriter = new PemWriter(new BufferedWriter(new FileWriter(publicKeyFile))); publicPemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded())); publicPemWriter.flush(); publicPemWriter.close(); PemWriter privatePemWriter = new PemWriter(new BufferedWriter(new FileWriter(privateKeyFile))); privatePemWriter.writeObject(new PemObject("RSA PRIVATE KEY", keyPair.getPrivate().getEncoded())); privatePemWriter.flush(); privatePemWriter.close(); } if (!publicKeyFile.exists()) { throw new PublicKeyFileNotFoundException(); } if (!privateKeyFile.exists()) { throw new PrivateKeyFileNotFoundException(); } PemReader publicKeyPemReader = new PemReader(new BufferedReader(new FileReader(publicKeyFile))); PemReader privateKeyPemReader = new PemReader(new BufferedReader(new FileReader(privateKeyFile))); PemObject publicPemObject = publicKeyPemReader.readPemObject(); if (publicPemObject == null) { throw new InvalidPublicKeyFileException(); } PemObject privatePemObject = privateKeyPemReader.readPemObject(); if (privatePemObject == null) { throw new InvalidPrivateKeyFileException(); } keyPair = new KeyPair(RsaUtils.bytesToPublicKey(publicPemObject.getContent()), RsaUtils.bytesToPrivateKey(privatePemObject.getContent())); publicKeyPemReader.close(); privateKeyPemReader.close(); rconConfigs = new ArrayList<RconConfig>(); for (int i = 0; i < config.getJSONArray("rcon-list").length(); i++) { JSONObject jsonObject = config.getJSONArray("rcon-list").getJSONObject(i); RconConfig rconConfig = new RconConfig( new InetSocketAddress(jsonObject.getString("ip"), jsonObject.getInt("port")), jsonObject.getString("password")); for (int j = 0; j < jsonObject.getJSONArray("commands").length(); j++) { rconConfig.getCommands().add(jsonObject.getJSONArray("commands").getString(j)); } rconConfigs.add(rconConfig); } loaded = true; if (save) { save(); } }
From source file:com.jaspersoft.jasperserver.api.metadata.common.util.RepositoryFileObject.java
@Override protected InputStream doGetInputStream() throws Exception { if (fileResource == null) { throw new JSException("no resource. URI: " + getName()); }/* www .ja v a 2s. c o m*/ InputStream data = resourceData != null ? resourceData.getDataStream() : fileResource.getDataStream(); // TODO: Should this be cached? InputStream in = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedOutputStream bufferedOut = new BufferedOutputStream(out); try { in = new BufferedInputStream(data); byte[] buf = new byte[10000]; int numRead = 0; while ((numRead = in.read(buf)) != -1) { bufferedOut.write(buf, 0, numRead); } } finally { if (in != null) { in.close(); } bufferedOut.flush(); } return new BufferedInputStream(new ByteArrayInputStream(out.toByteArray())); }
From source file:es.mityc.firmaJava.configuracion.Configuracion.java
/** * Este mtodo guarda la configuracin en el fichero SignXML.properties * @throws IOException // www .jav a 2 s.c o m */ public void guardarConfiguracion() throws IOException { StringBuffer paraGrabar = new StringBuffer(); String linea; // La configuracin siempre se guarda en un fichero externo File dir = new File(System.getProperty(USER_HOME) + File.separator + getNombreDirExterno()); if ((!dir.exists()) || (!dir.isDirectory())) { if (!dir.mkdir()) return; } File fichero = new File(dir, getNombreFicheroExterno()); log.trace("Salva fichero de configuracin en: " + fichero.getAbsolutePath()); if (!fichero.exists()) { // Si el fichero externo no existe se crea fuera un copia // del fichero almacenado dentro del jar InputStream fis = getClass().getResourceAsStream(FICHERO_PROPIEDADES); BufferedInputStream bis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream(fichero); BufferedOutputStream bos = new BufferedOutputStream(fos); int length = bis.available(); byte[] datos = new byte[length]; bis.read(datos); bos.write(datos); bos.flush(); bos.close(); bis.close(); } // AppPerfect: Falso positivo BufferedReader propiedades = new BufferedReader(new FileReader(fichero)); linea = propiedades.readLine(); while (linea != null) { StringTokenizer token = new StringTokenizer(linea, IGUAL); if (token.hasMoreTokens()) { String clave = token.nextToken().trim(); if (configuracion.containsKey(clave)) { paraGrabar.append(clave); paraGrabar.append(IGUAL_ESPACIADO); paraGrabar.append(getValor(clave)); paraGrabar.append(CRLF); } else { paraGrabar.append(linea); paraGrabar.append(CRLF); } } else paraGrabar.append(CRLF); linea = propiedades.readLine(); } propiedades.close(); //AppPerfect: Falso positivo FileWriter fw = new FileWriter(fichero); BufferedWriter bw = new BufferedWriter(fw); bw.write(String.valueOf(paraGrabar)); bw.flush(); bw.close(); }
From source file:com.twotoasters.android.horizontalimagescroller.io.ImageCacheManager.java
private void putBitmapToCaches(InputStream is, ImageUrlRequest imageUrlRequest) throws IOException { FlushedInputStream fis = new FlushedInputStream(is); Bitmap bitmap = null;//from w w w.j a v a 2s . c o m try { bitmap = BitmapHelper.decodeSampledBitmapFromSteam(fis, imageUrlRequest.getReqWidth(), imageUrlRequest.getReqHeight()); memoryCache.put(imageUrlRequest.getCacheKey(), bitmap); } catch (OutOfMemoryError e) { Log.v(TAG, "writeToExternalStorage - Out of memory"); System.gc(); } if (bitmap != null) { createFileIfNonexistent(imageUrlRequest); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(openImageFileByUrl(imageUrlRequest)), 65535); bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos); bos.flush(); bos.close(); } fis.close(); is.close(); }
From source file:eu.scape_project.arc2warc.identification.PayloadContent.java
private byte[] inputStreamToByteArray() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedInputStream buffis = new BufferedInputStream(inputStream); BufferedOutputStream buffos = new BufferedOutputStream(baos); byte[] tempBuffer = new byte[BUFFER_SIZE]; int bytesRead; boolean firstByteArray = true; while ((bytesRead = buffis.read(tempBuffer)) != -1) { buffos.write(tempBuffer, 0, bytesRead); if (applyIdentification && firstByteArray && tempBuffer != null && bytesRead > 0) { identified = identifyPayloadType(tempBuffer); }/* w w w .j a v a2s. co m*/ firstByteArray = false; } buffis.close(); buffos.flush(); buffos.close(); return baos.toByteArray(); }
From source file:com.fluidops.iwb.deepzoom.ImageLoader.java
/** * Loads an image from a URL to a local file * @param url - The URL from which to obtain the image * @param file - The file to store the image to * @return// w w w .ja v a2 s . c o m */ public boolean loadImage(String url, File file) { URL u; InputStream is = null; BufferedInputStream dis = null; int b; try { try { u = new URL(url); } catch (MalformedURLException e) { // this is the case if we work with relative URLs (in eCM) // just prepend the base URL# u = new URL(serverURL + url); } try { is = u.openStream(); } catch (IOException e) { System.out.println("File could not be found: " + url); // quick fix: 200px-Image n/a, try smaller pic (for Wikipedia images) url = url.replace("200px", "94px"); u = new URL(url); try { is = u.openStream(); } catch (IOException e2) { System.out.println("also smaller image not available"); return false; } } dis = new BufferedInputStream(is); BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); while ((b = dis.read()) != -1) { out.write(b); } out.flush(); } finally { IOUtils.closeQuietly(out); } } catch (MalformedURLException mue) { logger.error(mue.getMessage(), mue); return false; } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); return false; } finally { IOUtils.closeQuietly(dis); } return true; }