List of usage examples for java.nio.channels FileChannel close
public final void close() throws IOException
From source file:org.yamj.core.service.file.tools.FileTools.java
/** * Copy the source file to the destination * * @param src/* w ww . j av a 2 s . co m*/ * @param dst * @return */ public static boolean copyFile(File src, File dst) { boolean returnValue = Boolean.FALSE; if (!src.exists()) { LOG.error("The file '{}' does not exist", src); return returnValue; } if (dst.isDirectory()) { makeDirectories(dst); returnValue = copyFile(src, new File(dst + File.separator + src.getName())); } else { FileInputStream inSource = null; FileOutputStream outSource = null; FileChannel inChannel = null; FileChannel outChannel = null; try { // gc: copy using file channels, potentially much faster inSource = new FileInputStream(src); outSource = new FileOutputStream(dst); inChannel = inSource.getChannel(); outChannel = outSource.getChannel(); long p = 0, s = inChannel.size(); while (p < s) { p += inChannel.transferTo(p, 1024 * 1024, outChannel); } return Boolean.TRUE; } catch (IOException error) { LOG.error("Failed copying file '{}' to '{}'", src, dst); LOG.error("File copying error", error); returnValue = Boolean.FALSE; } finally { if (inChannel != null) { try { inChannel.close(); } catch (IOException ex) { // Ignore } } if (inSource != null) { try { inSource.close(); } catch (IOException ex) { // Ignore } } if (outChannel != null) { try { outChannel.close(); } catch (IOException ex) { // Ignore } } if (outSource != null) { try { outSource.close(); } catch (IOException ex) { // Ignore } } } } return returnValue; }
From source file:org.lexgrid.loader.writer.NoClosingRootTagStaxEventItemWriter.java
@Override public void close() { super.close(); String rootTag = "</" + getRootTagName() + ">"; String xml = null;//from w w w . j a v a 2 s . c om try { xml = FileUtils.readFileToString(xmlFile); } catch (IOException e) { throw new RuntimeException(e); } if (!xml.endsWith(rootTag)) { try { FileOutputStream os = new FileOutputStream(xmlFile, true); FileChannel channel = os.getChannel(); ByteBuffer byteBuffer = ByteBuffer.wrap(rootTag.getBytes()); channel.write(byteBuffer); channel.close(); xml = FileUtils.readFileToString(xmlFile); } catch (IOException ioe) { throw new RuntimeException(ioe); } } }
From source file:com.stimulus.archiva.store.MessageStore.java
public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try {/* w ww .j a v a2 s . com*/ in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
From source file:me.carpela.network.pt.cracker.tools.ttorrent.Torrent.java
private static String hashFiles(List<File> files, int pieceLenght) throws InterruptedException, IOException, NoSuchAlgorithmException { int threads = getHashingThreadsCount(); ExecutorService executor = Executors.newFixedThreadPool(threads); ByteBuffer buffer = ByteBuffer.allocate(pieceLenght); List<Future<String>> results = new LinkedList<Future<String>>(); StringBuilder hashes = new StringBuilder(); long length = 0L; int pieces = 0; long start = System.nanoTime(); for (File file : files) { length += file.length();/* ww w. j ava2 s . c o m*/ FileInputStream fis = new FileInputStream(file); FileChannel channel = fis.getChannel(); int step = 10; try { while (channel.read(buffer) > 0) { if (buffer.remaining() == 0) { buffer.clear(); results.add(executor.submit(new CallableChunkHasher(buffer))); } if (results.size() >= threads) { pieces += accumulateHashes(hashes, results); } if (channel.position() / (double) channel.size() * 100f > step) { step += 10; } } } finally { channel.close(); fis.close(); } } // Hash the last bit, if any if (buffer.position() > 0) { buffer.limit(buffer.position()); buffer.position(0); results.add(executor.submit(new CallableChunkHasher(buffer))); } pieces += accumulateHashes(hashes, results); // Request orderly executor shutdown and wait for hashing tasks to // complete. executor.shutdown(); while (!executor.isTerminated()) { Thread.sleep(10); } long elapsed = System.nanoTime() - start; int expectedPieces = (int) (Math.ceil((double) length / pieceLenght)); return hashes.toString(); }
From source file:org.lnicholls.galleon.util.Tools.java
public static void copy(File src, File dst) { try {//from w ww. j av a2 s . com FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); srcChannel = null; dstChannel.close(); dstChannel = null; } catch (IOException ex) { Tools.logException(Tools.class, ex, dst.getAbsolutePath()); } }
From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java
/** * Source://from w w w . j a va 2 s .c o m * http://stackoverflow.com/questions/4349075/bitmapfactory-decoderesource * -returns-a-mutable-bitmap-in-android-2-2-and-an-immu * * Converts a immutable bitmap to a mutable bitmap. This operation doesn't * allocates more memory that there is already allocated. * * @param imgIn * - Source image. It will be released, and should not be used * more * @return a copy of imgIn, but immutable. */ public static Bitmap convertBitmapToMutable(Bitmap imgIn) { try { // this is the file going to use temporally to save the bytes. // This file will not be a image, it will store the raw image data. File file = new File(MyApp.context.getFilesDir() + File.separator + "temp.tmp"); // Open an RandomAccessFile // Make sure you have added uses-permission // android:name="android.permission.WRITE_EXTERNAL_STORAGE" // into AndroidManifest.xml file RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); // get the width and height of the source bitmap. int width = imgIn.getWidth(); int height = imgIn.getHeight(); Config type = imgIn.getConfig(); // Copy the byte to the file // Assume source bitmap loaded using options.inPreferredConfig = // Config.ARGB_8888; FileChannel channel = randomAccessFile.getChannel(); MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, imgIn.getRowBytes() * height); imgIn.copyPixelsToBuffer(map); // recycle the source bitmap, this will be no longer used. imgIn.recycle(); System.gc();// try to force the bytes from the imgIn to be released // Create a new bitmap to load the bitmap again. Probably the memory // will be available. imgIn = Bitmap.createBitmap(width, height, type); map.position(0); // load it back from temporary imgIn.copyPixelsFromBuffer(map); // close the temporary file and channel , then delete that also channel.close(); randomAccessFile.close(); // delete the temporary file file.delete(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return imgIn; }
From source file:org.apache.usergrid.chop.runner.drivers.ResultsLog.java
@Override public void truncate() throws IOException { if (isOpen.get()) { throw new IOException("Cannot truncate while log is open for writing. Close the log then truncate."); }// w w w. j a v a 2s. co m // Synchronize on isOpen to prevent re-opening while truncating (rare) synchronized (isOpen) { File results = new File(resultsFile.get()); FileChannel channel = new FileOutputStream(results, true).getChannel(); channel.truncate(0); channel.close(); resultCount.set(0); } }
From source file:com.thinkberg.moxo.vfs.s3.jets3t.Jets3tFileObject.java
protected void doAttach() throws Exception { if (!attached) { try {//from w w w .ja va 2 s. co m object = service.getObject(bucket, getS3Key()); System.err.println("Attached file to S3 Object: " + object); InputStream is = object.getDataInputStream(); if (object.getContentLength() > 0) { ReadableByteChannel rbc = Channels.newChannel(is); FileChannel cacheFc = getCacheFileChannel(); cacheFc.transferFrom(rbc, 0, object.getContentLength()); cacheFc.close(); rbc.close(); } else { is.close(); } } catch (S3ServiceException e) { object = new S3Object(bucket, getS3Key()); object.setLastModifiedDate(new Date()); System.err.println("Attached file to new S3 Object: " + object); } attached = true; } }
From source file:gov.nih.nci.firebird.selenium2.framework.AbstractFirebirdWebDriverTest.java
private void truncateJbossLog() throws IOException { FileChannel outChan = new FileOutputStream(serverLog, true).getChannel(); outChan.truncate(0);//from w w w. ja v a2 s . c om outChan.close(); }
From source file:org.loadosophia.client.LoadosophiaAPIClient.java
protected String[] multipartPost(LinkedList<Part> parts, String URL, int expectedSC) throws IOException { log.debug("Request POST: " + URL); parts.add(new StringPart("token", token)); PostMethod postRequest = new PostMethod(URL); MultipartRequestEntity multipartRequest = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), postRequest.getParams());//from www . java 2 s . co m postRequest.setRequestEntity(multipartRequest); int result = httpClient.executeMethod(postRequest); if (result != expectedSC) { String fname = File.createTempFile("error_", ".html").getAbsolutePath(); notifier.notifyAbout("Saving server error response to: " + fname); FileOutputStream fos = new FileOutputStream(fname); FileChannel resultFile = fos.getChannel(); resultFile.write(ByteBuffer.wrap(postRequest.getResponseBody())); resultFile.close(); throw new HttpException("Request returned not " + expectedSC + " status code: " + result); } byte[] bytes = postRequest.getResponseBody(); if (bytes == null) { bytes = new byte[0]; } String response = new String(bytes); return response.trim().split(";"); }