List of usage examples for java.io FileOutputStream getChannel
public FileChannel getChannel()
From source file:org.yamj.core.service.file.tools.FileTools.java
/** * Copy the source file to the destination * * @param src/* ww w . j av a 2 s. c o 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:com.log4ic.compressor.utils.FileUtils.java
/** * ?// w w w . j ava 2s .c o m * * @param content * @param filePath * @return */ public static File writeFile(byte[] content, String filePath) { FileOutputStream out = null; FileChannel outChannel = null; File file = new File(filePath); if (file.exists()) { file.delete(); } if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } ByteBuffer outBuffer = ByteBuffer.allocate(content.length); outBuffer.put(content); outBuffer.flip(); try { out = new FileOutputStream(file); outChannel = out.getChannel(); outChannel.write(outBuffer); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (outChannel != null) { try { outChannel.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.flush(); } catch (IOException e) { e.printStackTrace(); } try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } return file.exists() ? file : null; }
From source file:maspack.fileutil.SafeFileUtils.java
/** * Internal copy file method./*from w w w.ja v a2 s . c o m*/ * * @param srcFile * the validated source file, must not be {@code null} * @param destFile * the validated destination file, must not be {@code null} * @param options * determine whether to use a file lock, and preserve date information * @throws IOException * if an error occurs */ private static void doCopyFile(File srcFile, File destFile, int options) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } File lockFile = new File(destFile.getAbsolutePath() + LOCK_EXTENSION); FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; // Create lock before starting transfer // NOTE: we are purposely not using the Java NIO FileLock, because that // is automatically removed when the JVM exits. We want this file to // persist to inform the system the transfer was never completed. if ((options & LOCK_FILE) != 0) { if (lockFile.exists()) { // if we are not cleaning old locks, throw error if ((options & CLEAN_LOCK) == 0) { throw new IOException( "Lock file exists, preventing a write to " + destFile.getAbsolutePath() + ". Delete " + lockFile.getName() + " or set the CLEAN_LOCK option flag"); } } else { lockFile.createNewFile(); // will always return true or throw // error } } while (pos < size) { count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos; pos += output.transferFrom(input, pos, count); } } finally { closeQuietly(output); closeQuietly(fos); closeQuietly(input); closeQuietly(fis); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if ((options & PRESERVE_DATE) != 0) { destFile.setLastModified(srcFile.lastModified()); } // successful copy, delete lock file deleteQuietly(lockFile); }
From source file:org.jab.docsearch.utils.FileUtils.java
/** * Copy file/* w ww . ja v a 2 s . c o m*/ * * @param sourceFilename source file * @param destinationFilename destination file */ public static boolean copyFile(String sourceFilename, String destinationFilename) { if (sourceFilename == null) { logger.warn("copyFile() failed because sourceFilename is null"); return false; } if (destinationFilename == null) { logger.warn("copyFile() failed because destinationFilename is null"); return false; } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { // open stream and channel from input fis = new FileInputStream(sourceFilename); fcin = fis.getChannel(); // open stream and channel from output fos = new FileOutputStream(destinationFilename); fcout = fos.getChannel(); fcin.transferTo(0, fcin.size(), fcout); return true; } catch (IOException ioe) { logger.fatal("copyFile() failed", ioe); return false; } catch (SecurityException se) { logger.fatal("copyFile() failed", se); return false; } finally { try { if (fcin != null) { fcin.close(); } } catch (IOException ioe) { logger.fatal("copyFile() can't close FileChannel"); } try { if (fis != null) { fis.close(); } } catch (IOException ioe) { logger.fatal("copyFile() can't close FileInputStream"); } try { if (fcout != null) { fcout.close(); } } catch (IOException ioe) { logger.fatal("copyFile() can't close FileChannel"); } try { if (fos != null) { fos.close(); } } catch (IOException ioe) { logger.fatal("copyFile() can't close FileOutputStream"); } } }
From source file:com.igormaznitsa.jcp.utils.PreprocessorUtils.java
public static void copyFile(@Nonnull final File source, @Nonnull final File dest, final boolean copyFileAttributes) throws IOException { assertNotNull("Source is null", source); assertNotNull("Destination file is null", dest); if (source.isDirectory()) { throw new IllegalArgumentException("Source file is directory"); }//from w w w . j a va 2 s .co m if (!dest.getParentFile().exists() && !dest.getParentFile().mkdirs()) { throw new IOException("Can't make directory [" + getFilePath(dest.getParentFile()) + ']'); } FileChannel fileSrc = null; FileChannel fileDst = null; final FileInputStream fileSrcInput = new FileInputStream(source); FileOutputStream fileOutput = null; try { fileSrc = fileSrcInput.getChannel(); fileOutput = new FileOutputStream(dest); fileDst = fileOutput.getChannel(); long size = fileSrc.size(); long pos = 0L; while (size > 0) { final long written = fileSrc.transferTo(pos, size, fileDst); pos += written; size -= written; } } finally { IOUtils.closeQuietly(fileSrcInput); IOUtils.closeQuietly(fileOutput); IOUtils.closeQuietly(fileDst); IOUtils.closeQuietly(fileSrc); } if (copyFileAttributes) { copyFileAttributes(source, dest); } }
From source file:cd.education.data.collector.android.utilities.FileUtils.java
private static String actualCopy(File sourceFile, File destFile) { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; FileChannel src = null;/*w w w . ja v a 2 s .c o m*/ FileChannel dst = null; try { fileInputStream = new FileInputStream(sourceFile); src = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destFile); dst = fileOutputStream.getChannel(); dst.transferFrom(src, 0, src.size()); dst.force(true); return null; } catch (FileNotFoundException e) { Log.e(t, "FileNotFoundException while copying file", e); return e.getMessage(); } catch (IOException e) { Log.e(t, "IOException while copying file", e); return e.getMessage(); } catch (Exception e) { Log.e(t, "Exception while copying file", e); return e.getMessage(); } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(fileOutputStream); IOUtils.closeQuietly(src); IOUtils.closeQuietly(dst); } }
From source file:it.geosolutions.tools.io.file.IOUtils.java
/** * This method is responsible for checking if the input file is still being * written or if its available for being parsed. * /*from www. j a v a 2 s . c om*/ * <p> * Specifically this method tries to open up a "rw" channel on the provided * input file. If the file is still being written this operation fails with * an exception, we therefore catch this exception and sleep for * {@value #ATOMIC_WAIT} seconds as defined in the constant * {@link #ATOMIC_WAIT}. * * <p> * If after having waited for {@link MAX_WAITING_TIME_FOR_LOCK} (which is * read from the configuration or set to the default value of * {@link #DEFAULT_WAITING_TIME}) we have not yet acquired the channel we * skip this file but we signal this situation. * * NOTE: To make use of mandatory locks, mandatory locking must be enabled * both on the file system that contains the file to be locked, and on the * file itself. Mandatory locking is enabled on a file system using the * "-o mand" option to mount(8), or the MS_MANDLOCK flag for mount(2). * Mandatory locking is enabled on a file by disabling group execute * permission on the file and enabling the set-group-ID permission bit (see * chmod(1) and chmod(2)). * * @param caller * @param inputFile * @param maxwait * @return <code>true</code> if the lock has been successfully acquired. * <code>false</code> otherwise * @throws InterruptedException * @throws IOException */ public static boolean acquireLock(Object caller, File inputFile, final long maxwait) throws InterruptedException, IOException { if (!inputFile.exists()) return false;// file not exists! if (inputFile.isDirectory()) { // return inputFile.setReadOnly(); return true;// cannot lock directory } // // // // Acquire an exclusive lock to wait for long // writing processes before trying to check on them // // // double sumWait = 0; while (true) { FileOutputStream outStream = null; FileChannel channel = null; FileLock lock = null; try { outStream = new FileOutputStream(inputFile, true); // get a rw channel channel = outStream.getChannel(); if (channel != null) { // here we could block lock = channel.tryLock(); if (lock != null) { if (LOGGER.isTraceEnabled()) LOGGER.trace("File locked successfully"); return true; } } } catch (OverlappingFileLockException e) { // File is already locked in this thread or virtual machine if (LOGGER.isDebugEnabled()) LOGGER.debug("File is already locked in this thread or virtual machine"); } catch (Exception e) { if (LOGGER.isDebugEnabled()) LOGGER.debug(e.getLocalizedMessage(), e); } finally { org.apache.commons.io.IOUtils.closeQuietly(outStream); // release the lock if (lock != null) try { lock.release(); } catch (Exception e) { // eat me } if (channel != null) try { channel.close(); } catch (Exception e) { // eat me } } // Sleep for ATOMIC_WAIT milliseconds prior to retry for acquiring // the lock synchronized (caller) { caller.wait(Conf.ATOMIC_WAIT); } sumWait += Conf.ATOMIC_WAIT; if (sumWait > maxwait) { if (LOGGER.isWarnEnabled()) LOGGER.warn("Waiting time beyond maximum specified waiting time, exiting..."); // Quitting the loop break; } } // A time greater than MAX_WAITING_TIME_FOR_LOCK has elapsed and no lock // has // been acquired. Thus, I need to return false return false; }
From source file:com.mods.grx.settings.utils.Utils.java
public static void file_copy(File ori_file, File dest_file) { try {// www . j ava 2 s .co m FileInputStream i_s = new FileInputStream(ori_file); FileOutputStream o_s = new FileOutputStream(dest_file); FileChannel inChannel = i_s.getChannel(); FileChannel outChannel = o_s.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); i_s.close(); o_s.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.solmix.commons.util.Files.java
/** * ?//w w w . j a v a 2s .c o m * * @param f1 * ? * @param f2 * * @throws Exception */ public static void copyFile(File f1, File f2) throws Exception { int length = 2097152; FileInputStream in = new FileInputStream(f1); FileOutputStream out = new FileOutputStream(f2); FileChannel inC = in.getChannel(); FileChannel outC = out.getChannel(); ByteBuffer b = null; while (true) { if (inC.position() == inC.size()) { inC.close(); outC.close(); } if ((inC.size() - inC.position()) < length) { length = (int) (inC.size() - inC.position()); } else length = 2097152; b = ByteBuffer.allocateDirect(length); inC.read(b); b.flip(); outC.write(b); outC.force(false); } }
From source file:org.apache.nifi.file.FileUtils.java
/** * Randomly generates a sequence of bytes and overwrites the contents of the * file a number of times. The file is then deleted. * * @param file File to be overwritten a number of times and, ultimately, * deleted// w w w . j ava 2 s . c o m * @param passes Number of times file should be overwritten * @throws IOException if something makes shredding or deleting a problem */ public static void shredFile(final File file, final int passes) throws IOException { final Random generator = new Random(); final long fileLength = file.length(); final int byteArraySize = (int) Math.min(fileLength, 1048576); // 1MB final byte[] b = new byte[byteArraySize]; final long numOfRandomWrites = (fileLength / b.length) + 1; final FileOutputStream fos = new FileOutputStream(file); try { // Over write file contents (passes) times final FileChannel channel = fos.getChannel(); for (int i = 0; i < passes; i++) { generator.nextBytes(b); for (int j = 0; j <= numOfRandomWrites; j++) { fos.write(b); } fos.flush(); channel.position(0); } // Write out "0" for each byte in the file Arrays.fill(b, (byte) 0); for (int j = 0; j < numOfRandomWrites; j++) { fos.write(b); } fos.flush(); fos.close(); // Try to delete the file a few times if (!FileUtils.deleteFile(file, null, 5)) { throw new IOException("Failed to delete file after shredding"); } } finally { FileUtils.closeQuietly(fos); } }