List of usage examples for java.io FileOutputStream getChannel
public FileChannel getChannel()
From source file:com.linuxbox.enkive.archiver.AbstractMessageArchivingService.java
private String saveToDisk(String messageData, String fileName) throws FailedToEmergencySaveException, SaveFileAlreadyExistsException { File emergencySaveFile = null; String emergencySaveFilePath = "UNKNOWN"; BufferedWriter out = null;//from www . ja v a 2s. c o m FileOutputStream fileStream = null; try { emergencySaveFile = new File(getEmergencySaveRoot(), fileName); emergencySaveFilePath = emergencySaveFile.getCanonicalPath(); fileStream = new FileOutputStream(emergencySaveFile); FileLock lock = null; try { lock = fileStream.getChannel().tryLock(); if (lock == null) { throw new SaveFileAlreadyExistsException(emergencySaveFilePath); } out = new BufferedWriter(new OutputStreamWriter(fileStream)); out.write(messageData); if (LOGGER.isInfoEnabled()) { LOGGER.info("Saved message to file: \"" + emergencySaveFilePath + "\""); } return emergencySaveFilePath; } finally { if (lock != null) { lock.release(); } } } catch (IOException e) { LOGGER.fatal("Emergency save to disk failed. ", e); throw new FailedToEmergencySaveException(e); } finally { try { if (out != null) { out.close(); } else if (fileStream != null) { fileStream.close(); } } catch (IOException e) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Could not close emergency save file \"" + emergencySavePath + "\"."); } } } }
From source file:org.totschnig.myexpenses.util.Utils.java
public static boolean copy(File src, File dst) { FileInputStream srcStream = null; FileOutputStream dstStream = null; try {/*from w w w . ja v a2s . c om*/ srcStream = new FileInputStream(src); dstStream = new FileOutputStream(dst); dstStream.getChannel().transferFrom(srcStream.getChannel(), 0, srcStream.getChannel().size()); return true; } catch (FileNotFoundException e) { Log.e("MyExpenses", e.getLocalizedMessage()); return false; } catch (IOException e) { Log.e("MyExpenses", e.getLocalizedMessage()); return false; } finally { try { srcStream.close(); } catch (Exception e) { } try { dstStream.close(); } catch (Exception e) { } } }
From source file:io.spring.initializr.generator.ProjectGenerator.java
private File downloadExternalStructure(String urlStr, File file) throws IOException { URL url = new URL(urlStr); String filename = FilenameUtils.getBaseName(urlStr) + "." + FilenameUtils.getExtension(urlStr); log.info("Filename: " + filename); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); File f = new File(file, filename); FileOutputStream fos = new FileOutputStream(f); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close();//ww w . jav a2s . c o m rbc.close(); return f; }
From source file:org.wso2.carbon.identity.common.testng.CarbonBasedTestListener.java
private void copyDefaultConfigsIfNotExists(Class callerClass) { URL carbonXmlUrl = callerClass.getClassLoader().getResource("repository/conf/carbon.xml"); boolean needToCopyCarbonXml = false; if (carbonXmlUrl == null) { needToCopyCarbonXml = true;/*from www . j av a2s . c om*/ } else { File file = new File(carbonXmlUrl.getPath()); needToCopyCarbonXml = !file.exists(); } if (needToCopyCarbonXml) { try { //Copy default identity xml into temp location and use it. URL url = CarbonBasedTestListener.class.getClassLoader().getResource("repository/conf/carbon.xml"); InputStream inputStream = url.openStream(); ReadableByteChannel inputChannel = Channels.newChannel(inputStream); Path tmpDirPath = Paths.get(System.getProperty("java.io.tmpdir"), "tests", callerClass.getSimpleName()); Path repoConfPath = Paths.get(tmpDirPath.toUri().getPath(), "repository", "conf"); Path carbonXMLPath = repoConfPath.resolve("carbon.xml"); Path carbonXML = Files.createFile(carbonXMLPath); FileOutputStream fos = new FileOutputStream(carbonXML.toFile()); WritableByteChannel targetChannel = fos.getChannel(); //Transfer data from input channel to output channel ((FileChannel) targetChannel).transferFrom(inputChannel, 0, Short.MAX_VALUE); inputStream.close(); targetChannel.close(); fos.close(); System.setProperty(TestConstants.CARBON_CONFIG_DIR_PATH, tmpDirPath.toString()); } catch (IOException e) { log.error("Failed to copy carbon.xml", e); } } else { try { System.setProperty(TestConstants.CARBON_CONFIG_DIR_PATH, Paths.get(carbonXmlUrl.toURI()).getParent().toString()); } catch (URISyntaxException e) { log.error("Failed to copy path for carbon.xml", e); } } }
From source file:org.eclipse.orion.internal.server.servlets.xfer.ClientImport.java
/** * A put is used to send a chunk of a file. *///from w w w . jav a2 s. c o m void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int transferred = getTransferred(); int length = getLength(); int headerLength = Integer.valueOf(req.getHeader(ProtocolConstants.HEADER_CONTENT_LENGTH)); String rangeString = req.getHeader(ProtocolConstants.HEADER_CONTENT_RANGE); if (rangeString == null) rangeString = "bytes 0-" + (length - 1) + '/' + length; //$NON-NLS-1$ ContentRange range = ContentRange.parse(rangeString); if (length != range.getLength()) { fail(req, resp, "Chunk specifies an incorrect document length"); return; } if (range.getStartByte() > transferred) { fail(req, resp, "Chunk missing; Expected start byte: " + transferred); return; } if (range.getEndByte() < range.getStartByte()) { fail(req, resp, "Invalid range: " + rangeString); return; } int chunkSize = 1 + range.getEndByte() - range.getStartByte(); if (chunkSize != headerLength) { fail(req, resp, "Content-Range doesn't agree with Content-Length"); return; } byte[] chunk = readChunk(req, chunkSize); FileOutputStream fout = null; try { fout = new FileOutputStream(new File(getStorageDirectory(), FILE_DATA), true); FileChannel channel = fout.getChannel(); channel.position(range.getStartByte()); channel.write(ByteBuffer.wrap(chunk)); channel.close(); } finally { try { if (fout != null) fout.close(); } catch (IOException e) { //ignore secondary failure } } transferred = range.getEndByte() + 1; setTransferred(transferred); save(); if (transferred >= length) { completeTransfer(req, resp); return; } resp.setStatus(308);//Resume Incomplete resp.setHeader("Range", "bytes 0-" + range.getEndByte()); //$NON-NLS-2$ setResponseLocationHeader(req, resp); }
From source file:com.splout.db.dnode.Fetcher.java
/** * In case of interrupted, written file is not deleted. */// w ww. j a v a 2s . c o m private void copyFile(File sourceFile, File destFile, Reporter reporter) throws IOException, InterruptedException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; Throttler throttler = new Throttler((double) bytesPerSecThrottle); FileInputStream iS = null; FileOutputStream oS = null; try { iS = new FileInputStream(sourceFile); oS = new FileOutputStream(destFile); source = iS.getChannel(); destination = oS.getChannel(); long bytesSoFar = 0; long reportingBytesSoFar = 0; long size = source.size(); int transferred = 0; while (bytesSoFar < size) { // Needed to being able to be interrupted at any moment. if (Thread.interrupted()) { throw new InterruptedException(); } // Casting to int here is safe since we will transfer at most "downloadBufferSize" bytes. // This is done on purpose for being able to implement Throttling. transferred = (int) destination.transferFrom(source, bytesSoFar, downloadBufferSize); bytesSoFar += transferred; reportingBytesSoFar += transferred; throttler.incrementAndThrottle(transferred); if (reportingBytesSoFar >= bytesToReportProgress) { reporter.progress(reportingBytesSoFar); reportingBytesSoFar = 0l; } } if (reporter != null) { reporter.progress(reportingBytesSoFar); } } catch (InterruptedException e) { e.printStackTrace(); } finally { if (iS != null) { iS.close(); } if (oS != null) { oS.close(); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
From source file:org.paxle.crawler.fs.impl.FsCrawler.java
private File copyChanneled(final File file, final ICrawlerDocument cdoc, final boolean useFsync) { logger.info(String.format("Copying '%s' using the copy mechanism of the OS%s", file, (useFsync) ? " with fsync" : "")); final ITempFileManager tfm = this.contextLocal.getCurrentContext().getTempFileManager(); if (tfm == null) { cdoc.setStatus(ICrawlerDocument.Status.UNKNOWN_FAILURE, "Cannot access ITempFileMananger from " + Thread.currentThread().getName()); return null; }//from w w w .jav a 2 s . c o m FileInputStream fis = null; FileOutputStream fos = null; File out = null; try { out = tfm.createTempFile(); fis = new FileInputStream(file); fos = new FileOutputStream(out); final FileChannel in_fc = fis.getChannel(); final FileChannel out_fc = fos.getChannel(); long txed = 0L; while (txed < in_fc.size()) txed += in_fc.transferTo(txed, in_fc.size() - txed, out_fc); if (useFsync) out_fc.force(false); out_fc.close(); try { detectFormats(cdoc, fis); } catch (IOException ee) { logger.warn( String.format("Error detecting format of '%s': %s", cdoc.getLocation(), ee.getMessage())); } } catch (IOException e) { logger.error(String.format("Error copying '%s' to '%s': %s", cdoc.getLocation(), out, e.getMessage()), e); cdoc.setStatus(ICrawlerDocument.Status.UNKNOWN_FAILURE, e.getMessage()); } finally { if (fis != null) try { fis.close(); } catch (IOException e) { /* ignore */} if (fos != null) try { fos.close(); } catch (IOException e) { /* ignore */} } return out; }
From source file:tilt.image.Picture.java
/** * Create a picture. Pictures stores links to the various image files. * @param options options from the geoJSON file * @param text the text to align with// w w w. java 2 s . co m * @param poster the ipaddress of the poster of the image (DDoS prevention) * @throws TiltException */ public Picture(Options options, TextIndex text, InetAddress poster) throws TiltException { try { URL url = new URL(options.url); // use url as id for now id = options.url; this.text = text; this.poster = poster; // try to register the picture PictureRegistry.register(this, options.url); // fetch picture from url ReadableByteChannel rbc = Channels.newChannel(url.openStream()); orig = File.createTempFile(PictureRegistry.PREFIX, PictureRegistry.SUFFIX); FileOutputStream fos = new FileOutputStream(orig); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); String mimeType = getFormatName(); if (!mimeType.equals(PNG_TYPE)) convertToPng(); this.options = options; this.coords = new Double[4][2]; for (int i = 0; i < 4; i++) { JSONArray vector = (JSONArray) options.coords.get(i); for (int j = 0; j < 2; j++) { this.coords[i][j] = (Double) vector.get(j); } } } catch (Exception e) { throw new TiltException(e); } }
From source file:org.apache.hadoop.hdfs.server.datanode.TestDirectoryScanner.java
/** * Truncate a block file/*w w w . jav a2 s. c o m*/ */ private long truncateBlockFile() throws IOException { synchronized (fds) { for (ReplicaInfo b : FsDatasetTestUtil.getReplicas(fds, bpid)) { File f = b.getBlockFile(); File mf = b.getMetaFile(); // Truncate a block file that has a corresponding metadata file if (f.exists() && f.length() != 0 && mf.exists()) { FileOutputStream s = null; FileChannel channel = null; try { s = new FileOutputStream(f); channel = s.getChannel(); channel.truncate(0); LOG.info("Truncated block file " + f.getAbsolutePath()); return b.getBlockId(); } finally { IOUtils.cleanup(LOG, channel, s); } } } } return 0; }
From source file:math.tools.Browse.java
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed FileOutputStream fos; new File(System.getProperty("user.home") + "//MathHelper//tools//" + table[jTable1.getSelectedRow()][0] + ".jar").delete(); try {/*from ww w . j a va 2 s .c o m*/ URL website = new URL("" + table[jTable1.getSelectedRow()][4]); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); fos = new FileOutputStream(System.getProperty("user.home") + "//MathHelper//tools//" + table[jTable1.getSelectedRow()][0] + ".jar"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (IOException ex) { Logger.getLogger(Browse.class.getName()).log(Level.SEVERE, null, ex); } try { Runtime.getRuntime().exec("java -jar " + System.getProperty("user.home") + "//MathHelper//tools//" + table[jTable1.getSelectedRow()][0] + ".jar"); } catch (IOException ex) { Logger.getLogger(Browse.class.getName()).log(Level.SEVERE, null, ex); } }