List of usage examples for java.io FileInputStream getChannel
public FileChannel getChannel()
From source file:org.solmix.commons.util.Files.java
/** * ?/*w ww .j a v a2 s .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
public static long copyFile(final File source, final OutputStream stream, final boolean closeOutputStream, final boolean lockInputFile) throws FileNotFoundException, IOException { FileInputStream fis = null; FileLock inLock = null;//from w ww. jav a 2 s . c o m long fileSize = 0L; try { fis = new FileInputStream(source); final FileChannel in = fis.getChannel(); if (lockInputFile) { inLock = in.tryLock(0, Long.MAX_VALUE, true); if (inLock == null) { throw new IOException("Unable to obtain exclusive file lock for: " + source.getAbsolutePath()); } } byte[] buffer = new byte[1 << 18]; //256 KB int bytesRead = -1; while ((bytesRead = fis.read(buffer)) != -1) { stream.write(buffer, 0, bytesRead); } in.force(false); stream.flush(); fileSize = in.size(); } finally { FileUtils.releaseQuietly(inLock); FileUtils.closeQuietly(fis); if (closeOutputStream) { FileUtils.closeQuietly(stream); } } return fileSize; }
From source file:org.datavaultplatform.common.io.FileCopy.java
/** * Internal copy file method.// w ww .j a va 2s .c o m * * @param progress the progress tracking object * @param srcFile the validated source file, must not be {@code null} * @param destFile the validated destination file, must not be {@code null} * @param preserveFileDate whether to preserve the file date * @throws IOException if an error occurs */ private static void doCopyFile(Progress progress, File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } 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; while (pos < size) { count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos; long copied = output.transferFrom(input, pos, count); pos += copied; progress.byteCount += copied; progress.timestamp = System.currentTimeMillis(); } } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(input); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } progress.fileCount += 1; }
From source file:org.fao.geonet.utils.BinaryFile.java
/** * Copies an input stream (from a file) to an output stream *//*from ww w. j a va 2 s.c o m*/ public static void copy(InputStream in, OutputStream out) throws IOException { if (in instanceof FileInputStream) { FileInputStream fin = (FileInputStream) in; WritableByteChannel outChannel; if (out instanceof FileOutputStream) { outChannel = ((FileOutputStream) out).getChannel(); } else { outChannel = Channels.newChannel(out); } fin.getChannel().transferTo(0, Long.MAX_VALUE, outChannel); } else { BufferedInputStream input = new BufferedInputStream(in); byte buffer[] = new byte[BUF_SIZE]; int nRead; while ((nRead = input.read(buffer)) > 0) out.write(buffer, 0, nRead); } }
From source file:com.parse.ParseFileUtils.java
/** * Internal copy file method.//from www. j ava2s .co m * This caches the original file length, and throws an IOException * if the output file length is different from the current input file length. * So it may fail if the file changes size. * It may also fail with "IllegalArgumentException: Negative size" if the input file is truncated part way * through copying the data and the new file size is less than the current position. * * @param srcFile the validated source file, must not be {@code null} * @param destFile the validated destination file, must not be {@code null} * @param preserveFileDate whether to preserve the file date * @throws IOException if an error occurs * @throws IOException if the output file length is not the same as the input file length after the copy completes * @throws IllegalArgumentException "Negative size" if the file is truncated so that the size is less than the position */ private static void doCopyFile(final File srcFile, final File destFile, final boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } 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(); final long size = input.size(); // TODO See IO-386 long pos = 0; long count = 0; while (pos < size) { final long remain = size - pos; count = remain > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : remain; final long bytesCopied = output.transferFrom(input, pos, count); if (bytesCopied == 0) { // IO-385 - can happen if file is truncated after caching the size break; // ensure we don't loop forever } pos += bytesCopied; } } finally { ParseIOUtils.closeQuietly(output); ParseIOUtils.closeQuietly(fos); ParseIOUtils.closeQuietly(input); ParseIOUtils.closeQuietly(fis); } final long srcLen = srcFile.length(); // TODO See IO-386 final long dstLen = destFile.length(); // TODO See IO-386 if (srcLen != dstLen) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "' Expected length: " + srcLen + " Actual: " + dstLen); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
From source file:org.archive.util.FileUtils.java
/** * Retrieve a number of lines from the file around the given * position, as when paging forward or backward through a file. * /*from w w w. j a v a 2 s. co m*/ * @param file File to retrieve lines * @param position offset to anchor lines * @param signedDesiredLineCount lines requested; if negative, * want this number of lines ending with a line containing * the position; if positive, want this number of lines, * all starting at or after position. * @param lines List<String> to insert found lines * @param lineEstimate int estimate of line size, 0 means use default * of 128 * @return LongRange indicating the file offsets corresponding to * the beginning of the first line returned, and the point * after the end of the last line returned * @throws IOException */ @SuppressWarnings("unchecked") public static LongRange pagedLines(File file, long position, int signedDesiredLineCount, List<String> lines, int lineEstimate) throws IOException { // consider negative positions as from end of file; -1 = last byte if (position < 0) { position = file.length() + position; } // calculate a reasonably sized chunk likely to have all desired lines if (lineEstimate == 0) { lineEstimate = 128; } int desiredLineCount = Math.abs(signedDesiredLineCount); long startPosition; long fileEnd = file.length(); int bufferSize = (desiredLineCount + 5) * lineEstimate; if (signedDesiredLineCount > 0) { // reading forward; include previous char in case line-end startPosition = position - 1; } else { // reading backward startPosition = position - bufferSize + (2 * lineEstimate); } if (startPosition < 0) { startPosition = 0; } if (startPosition + bufferSize > fileEnd) { bufferSize = (int) (fileEnd - startPosition); } // read that reasonable chunk FileInputStream fis = new FileInputStream(file); fis.getChannel().position(startPosition); byte[] buf = new byte[bufferSize]; ArchiveUtils.readFully(fis, buf); IOUtils.closeQuietly(fis); // find all line starts fully in buffer // (positions after a line-end, per line-end definition in // BufferedReader.readLine) LinkedList<Integer> lineStarts = new LinkedList<Integer>(); if (startPosition == 0) { lineStarts.add(0); } boolean atLineEnd = false; boolean eatLF = false; int i; for (i = 0; i < bufferSize; i++) { if ((char) buf[i] == '\n' && eatLF) { eatLF = false; continue; } if (atLineEnd) { atLineEnd = false; lineStarts.add(i); if (signedDesiredLineCount < 0 && startPosition + i > position) { // reached next line past position, read no more break; } } if ((char) buf[i] == '\r') { atLineEnd = true; eatLF = true; continue; } if ((char) buf[i] == '\n') { atLineEnd = true; } } if (startPosition + i == fileEnd) { // add phantom lineStart after end lineStarts.add(bufferSize); } int foundFullLines = lineStarts.size() - 1; // if found no lines if (foundFullLines < 1) { if (signedDesiredLineCount > 0) { if (startPosition + bufferSize == fileEnd) { // nothing more to read: return nothing return new LongRange(fileEnd, fileEnd); } else { // retry with larger lineEstimate return pagedLines(file, position, signedDesiredLineCount, lines, Math.max(bufferSize, lineEstimate)); } } else { // try again with much larger line estimate // TODO: fail gracefully before growing to multi-MB buffers return pagedLines(file, position, signedDesiredLineCount, lines, bufferSize); } } // trim unneeded lines while (signedDesiredLineCount > 0 && startPosition + lineStarts.getFirst() < position) { // discard lines starting before desired position lineStarts.removeFirst(); } while (lineStarts.size() > desiredLineCount + 1) { if (signedDesiredLineCount < 0 && (startPosition + lineStarts.get(1) <= position)) { // discard from front until reach line containing target position lineStarts.removeFirst(); } else { lineStarts.removeLast(); } } int firstLine = lineStarts.getFirst(); int partialLine = lineStarts.getLast(); LongRange range = new LongRange(startPosition + firstLine, startPosition + partialLine); List<String> foundLines = IOUtils .readLines(new ByteArrayInputStream(buf, firstLine, partialLine - firstLine)); if (foundFullLines < desiredLineCount && signedDesiredLineCount < 0 && startPosition > 0) { // if needed and reading backward, read more lines from earlier range = expandRange(range, pagedLines(file, range.getMinimumLong() - 1, signedDesiredLineCount + foundFullLines, lines, bufferSize / foundFullLines)); } lines.addAll(foundLines); if (signedDesiredLineCount < 0 && range.getMaximumLong() < position) { // did not get line containining start position range = expandRange(range, pagedLines(file, partialLine, 1, lines, bufferSize / foundFullLines)); } if (signedDesiredLineCount > 0 && foundFullLines < desiredLineCount && range.getMaximumLong() < fileEnd) { // need more forward lines range = expandRange(range, pagedLines(file, range.getMaximumLong(), desiredLineCount - foundFullLines, lines, bufferSize / foundFullLines)); } return range; }
From source file:com.opendesign.utils.CmnUtil.java
/** * ? //from w ww . j ava 2 s. c om * * @param oldFilePath * @param newFilePath */ public static void fileCopy(String oldFilePath, String newFilePath) { File oldFile = new File(oldFilePath); File newFile = new File(newFilePath); try { FileInputStream inputStream = new FileInputStream(oldFile); FileOutputStream outputStream = new FileOutputStream(newFile); FileChannel fcin = inputStream.getChannel(); FileChannel fcout = outputStream.getChannel(); long size = fcin.size(); fcin.transferTo(0, size, fcout); fcout.close(); fcin.close(); outputStream.close(); inputStream.close(); } catch (Exception e) { } }
From source file:com.opendesign.utils.CmnUtil.java
/** * ? /* w ww . j ava 2 s .c o m*/ * * @param oldFilePath * @param oldFileName * @param newFilePath * @param newFileName */ public static void fileCopy(String oldFilePath, String oldFileName, String newFilePath, String newFileName) { File oldFile = new File(oldFilePath, oldFileName); File newFile = new File(newFilePath, newFileName); try { FileInputStream inputStream = new FileInputStream(oldFile); FileOutputStream outputStream = new FileOutputStream(newFile); FileChannel fcin = inputStream.getChannel(); FileChannel fcout = outputStream.getChannel(); long size = fcin.size(); fcin.transferTo(0, size, fcout); fcout.close(); fcin.close(); outputStream.close(); inputStream.close(); } catch (Exception e) { } }
From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.FileUtil.java
public static boolean copyFile(final String sourceFilename, final String destFilename) { boolean success = false; FileChannel source = null;/*from w w w . j ava 2 s .co m*/ FileChannel destination = null; FileInputStream sourceStream = null; FileOutputStream destinationStream = null; final File destFile = new File(destFilename); final File sourceFile = new File(sourceFilename); try { final long size = sourceFile.length(); sourceStream = new FileInputStream(sourceFile); destinationStream = new FileOutputStream(destFile); source = sourceStream.getChannel(); destination = destinationStream.getChannel(); long toTransfer = size; while (toTransfer > 0) { toTransfer -= source.transferTo(size - toTransfer, toTransfer, destination); } success = true; } catch (IOException iox) { try { logger.error( "Unable to copy " + sourceFile.getCanonicalPath() + " to " + destFile.getCanonicalPath(), iox); } catch (IOException iox2) { logger.error("Unable to copy " + sourceFile.getName() + " OR get the canonical name", iox2); } } finally { try { if (source != null) { source.close(); source = null; } if (destination != null) { destination.close(); destination = null; } if (sourceStream != null) { sourceStream.close(); sourceStream = null; } if (destinationStream != null) { destinationStream.close(); destinationStream = null; } } catch (IOException iox3) { logger.error("Unable to close stream?!?", iox3); } } return success; }
From source file:com.att.api.oauth.OAuthToken.java
/** * Attempts to load an OAuthToken from a file in an asynchronous-safe * manner.// w w w . ja v a2s .c o m * * <p> * If <code>fpath</code> does not exist or some required values are missing * from the saved file, null is returned. * </p> * * <p> * <strong>WARNING</strong>: Because caching may be used, manually modifying * the saved token properties file may yield unexpected results unless * caching is disabled. * </p> * * @param fpath file path from which to load token * @return OAuthToken an OAuthToken object if successful, null otherwise * @throws IOException if there was an error loading the token * @see #useTokenCaching(boolean) */ public static OAuthToken loadToken(String fpath) throws IOException { FileInputStream fInputStream = null; FileLock fLock = null; synchronized (LOCK_OBJECT) { // attempt to load from cached tokens, thereby saving file I/O if (cachedTokens != null && cachedTokens.get(fpath) != null) { return cachedTokens.get(fpath); } if (!new File(fpath).exists()) { return null; } try { fInputStream = new FileInputStream(fpath); // acquire shared lock fLock = fInputStream.getChannel().lock(0L, Long.MAX_VALUE, true); Properties props = new Properties(); props.load(fInputStream); if (!props.containsKey("creationTime") || !props.containsKey("expiresIn")) { return null; } String accessToken = props.getProperty("accessToken"); if (accessToken == null || accessToken.equals("")) { return null; } String refreshToken = props.getProperty("refreshToken"); String sExpiresIn = props.getProperty("expiresIn"); long expiresIn = new Long(sExpiresIn).longValue(); String sCreationTime = props.getProperty("creationTime"); long creationTime = new Long(sCreationTime).longValue(); return new OAuthToken(accessToken, expiresIn, refreshToken, creationTime); } catch (IOException e) { throw e; // pass along exception } finally { if (fLock != null) { fLock.release(); } if (fInputStream != null) { fInputStream.close(); } } } }