List of usage examples for java.nio.channels FileChannel close
public final void close() throws IOException
From source file:org.jajuk.util.UtilSystem.java
/** * Save a file in the same directory with name <filename>_YYYYmmddHHMM.xml and * with a given maximum Mb size for the file and its backup files * //from www . ja v a 2 s . c o m * @param file The file to back up * @param iMB */ public static void backupFile(final File file, final int iMB) { try { if (Integer.parseInt(Conf.getString(Const.CONF_BACKUP_SIZE)) <= 0) { // 0 or less means no backup return; } // calculates total size in MB for the file to backup and its // backup files long lUsedMB = 0; final List<File> alFiles = new ArrayList<File>(10); final File[] files = new File(file.getAbsolutePath()).getParentFile().listFiles(); if (files != null) { for (final File element : files) { if (element.getName().indexOf(UtilSystem.removeExtension(file.getName())) != -1) { lUsedMB += element.length(); alFiles.add(element); } } // sort found files alFiles.remove(file); Collections.sort(alFiles); // too much backup files, delete older if (((lUsedMB - file.length()) / 1048576 > iMB) && (alFiles.size() > 0)) { final File fileToDelete = alFiles.get(0); if (fileToDelete != null) { //NOSONAR if (!fileToDelete.delete()) { Log.warn("Could not delete file " + fileToDelete); } } } } // backup itself using nio, file name is // collection-backup-yyyMMdd.xml final String sExt = new SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(new Date()); final File fileNew = new File(UtilSystem.removeExtension(file.getAbsolutePath()) + "-backup-" + sExt + "." + UtilSystem.getExtension(file)); final FileChannel fcSrc = new FileInputStream(file).getChannel(); try { final FileChannel fcDest = new FileOutputStream(fileNew).getChannel(); try { fcDest.transferFrom(fcSrc, 0, fcSrc.size()); } finally { fcDest.close(); } } finally { fcSrc.close(); } } catch (final IOException ie) { Log.error(ie); } }
From source file:org.rzo.yajsw.os.ms.win.w32.WindowsJavaHome.java
/** * Copy file.//from www . j a v a 2s. c o m * * @param in * the in * @param out * the out * * @throws IOException * Signals that an I/O exception has occurred. */ void copyFile(File in, File out) throws IOException { System.out.println("copying : " + in.getAbsolutePath() + " -> " + out.getAbsolutePath()); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
From source file:org.gnucash.android.export.ExporterAsyncTask.java
/** * Copies a file from <code>src</code> to <code>dst</code> * @param src Absolute path to the source file * @param dst Absolute path to the destination file * @throws IOException if the file could not be copied *///from www. j a va 2 s . com public void copyFile(File src, File dst) throws IOException { //TODO: Make this asynchronous at some time, t in the future. if (mExportParams.getExportFormat() == ExportFormat.QIF) { splitQIF(src, dst); } else { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } }
From source file:com.baidu.rigel.biplatform.tesseract.util.FileUtils.java
/** * readFile/*w ww . j av a 2 s . co m*/ * * @param filePath ? * @return byte[] */ public static byte[] readFile(String filePath) { LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_BEGIN, "readFile", "[filePath:" + filePath + "]")); if (StringUtils.isEmpty(filePath)) { LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_EXCEPTION, "readFile", "[filePath:" + filePath + "]")); throw new IllegalArgumentException(); } File file = new File(filePath); FileInputStream fin = null; FileChannel fcin = null; ByteBuffer rbuffer = ByteBuffer.allocate(TesseractConstant.FILE_BLOCK_SIZE); ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (file.exists()) { try { fin = new FileInputStream(file); fcin = fin.getChannel(); while (fcin.read(rbuffer) != -1) { bos.write(rbuffer.array()); } } catch (Exception e) { LOGGER.error(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_EXCEPTION, "readFile", "[filePath:" + filePath + "]"), e); } finally { try { if (fin != null) { fin.close(); } if (fcin != null) { fcin.close(); } bos.close(); } catch (Exception e) { LOGGER.error(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_EXCEPTION, "readFile", "[filePath:" + filePath + "]"), e); } } } LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_END, "readFile", "[filePath:" + filePath + "]")); return bos.toByteArray(); }
From source file:org.jajuk.util.UtilSystem.java
/** * Additional file checksum used to prevent bug #886098. Simply return some * bytes read at the middle of the file/* w w w . j a va 2 s. com*/ * <p> * uses nio api for performances * * @param fio * * @return the file checksum * * @throws JajukException the jajuk exception */ public static String getFileChecksum(final File fio) throws JajukException { try { String sOut = ""; final FileChannel fc = new FileInputStream(fio).getChannel(); try { final ByteBuffer bb = ByteBuffer.allocate(500); fc.read(bb, fio.length() / 2); sOut = new String(bb.array()); } finally { fc.close(); } return MD5Processor.hash(sOut); } catch (final IOException e) { throw new JajukException(103, e); } }
From source file:org.gcaldaemon.core.Configurator.java
public static final void copyFile(File from, File to) throws Exception { if (from == null || to == null || !from.exists()) { return;//from ww w .j ava 2s .co m } RandomAccessFile fromFile = null; RandomAccessFile toFile = null; try { fromFile = new RandomAccessFile(from, "r"); toFile = new RandomAccessFile(to, "rw"); FileChannel fromChannel = fromFile.getChannel(); FileChannel toChannel = toFile.getChannel(); long length = fromFile.length(); long start = 0; while (start < length) { start += fromChannel.transferTo(start, length - start, toChannel); } fromChannel.close(); toChannel.close(); } finally { if (fromFile != null) { fromFile.close(); } if (toFile != null) { toFile.close(); } } }
From source file:ga.rugal.jpt.common.tracker.common.Torrent.java
private static String hashFiles(List<File> files, int pieceLenght) throws InterruptedException, IOException { int threads = getHashingThreadsCount(); ExecutorService executor = Executors.newFixedThreadPool(threads); ByteBuffer buffer = ByteBuffer.allocate(pieceLenght); List<Future<String>> results = new LinkedList<>(); StringBuilder hashes = new StringBuilder(); long length = 0L; int pieces = 0; long start = System.nanoTime(); for (File file : files) { LOG.info("Hashing data from {} with {} threads ({} pieces)...", new Object[] { file.getName(), threads, (int) (Math.ceil((double) file.length() / pieceLenght)) }); length += file.length();/*from w ww . ja v a2 s.com*/ 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) { LOG.info(" ... {}% complete", 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)); LOG.info("Hashed {} file(s) ({} bytes) in {} pieces ({} expected) in {}ms.", new Object[] { files.size(), length, pieces, expectedPieces, String.format("%.1f", elapsed / 1e6), }); return hashes.toString(); }
From source file:org.alfresco.repo.content.AbstractReadOnlyContentStoreTest.java
/** * Tests random access reading/*from ww w . ja v a2s.com*/ * <p> * Only executes if the reader implements {@link RandomAccessContent}. */ @Test public void testRandomAccessRead() throws Exception { ContentStore store = getStore(); String contentUrl = getExistingContentUrl(); if (contentUrl == null) { logger.warn("Store test testRandomAccessRead not possible on " + store.getClass().getName()); return; } // Get the reader ContentReader reader = store.getReader(contentUrl); assertNotNull("Reader should never be null", reader); FileChannel fileChannel = reader.getFileChannel(); assertNotNull("No channel given", fileChannel); // check that no other content access is allowed try { reader.getReadableChannel(); fail("Second channel access allowed"); } catch (RuntimeException e) { // expected } fileChannel.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; }/*w ww . j a v a 2s.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:org.forgerock.openidm.script.javascript.JavaScriptFactory.java
private Script initializeScript(String name, File source, boolean sharedScope) throws ScriptException { initDebugListener();//from w w w .ja v a2 s . c o m if (debugInitialised) { try { FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(getTargetFile(name)).getChannel(); FileLock outLock = outChannel.lock(); FileLock inLock = inChannel.lock(0, inChannel.size(), true); inChannel.transferTo(0, inChannel.size(), outChannel); outLock.release(); inLock.release(); inChannel.close(); outChannel.close(); } catch (IOException e) { logger.warn("JavaScript source was not updated for {}", name, e); } } return new JavaScript(name, source, sharedScope); }