List of usage examples for java.nio.channels FileChannel transferFrom
public abstract long transferFrom(ReadableByteChannel src, long position, long count) 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 * //www. j a v a 2 s . c om * @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:com.ettrema.zsync.UploadReader.java
/** * Copies a Range of blocks from rc into a new offset of wc * //from ww w.jav a 2s .c o m * @param rc A FileChannel for the input File * @param reloc The RelocateRange specifying the Range to be copied and its new offset * @param blockSize The block size used by reloc * @param wc The FileChannel for the output File * @throws IOException */ private static void moveRange(FileChannel rc, RelocateRange reloc, int blockSize, FileChannel wc) throws IOException { long MAX_BUFFER = 16384; long startBlock = reloc.getBlockRange().getStart(); long finishBlock = reloc.getBlockRange().getFinish(); long bytesLeft = (finishBlock - startBlock) * blockSize; //bytes left to copy long readAtOnce = 0; //number of bytes to attempt to read long bytesRead = 0; //number of bytes actually read long currOffset = reloc.getOffset(); //current write position if (finishBlock * blockSize > rc.size() || startBlock < 0) { throw new RuntimeException("Invalid RelocateRange: Source file does not contain blocks " + reloc.getBlockRange().getRange()); } rc.position(startBlock * blockSize); while (bytesLeft > 0) { readAtOnce = Math.min(bytesLeft, MAX_BUFFER); /*Because transferFrom does not update the write channel's position, * it needs to be set manually */ bytesRead = wc.transferFrom(rc, currOffset, readAtOnce); bytesLeft -= bytesRead; currOffset += bytesRead; } }
From source file:eu.prestoprime.plugin.p4.CopyTasks.java
@WfService(name = "master_file_first_copy", version = "2.0.0") public void masterFileFirstCopy(Map<String, String> sParams, Map<String, String> dParamsString, Map<String, File> dParamsFile) throws TaskExecutionFailedException { // get sipID/* www .j a va 2 s.c o m*/ String sipID = dParamsString.get("sipID"); SIP sip = null; try { // get sip sip = P4DataManager.getInstance().getSIPByID(sipID); String inputVideo = null; // get MQ file String[] formats = sParams.get("MQformats").split(","); for (String format : formats) { List<String> videoFileList = sip.getAVMaterial(format, "FILE"); if (videoFileList.size() > 0) { inputVideo = videoFileList.get(0); String outputVideoName = inputVideo.substring(inputVideo.lastIndexOf(File.separator) + 1); String outputVideo = dParamsString.get("videosFolder") + File.separator + outputVideoName; File inputFile = new File(inputVideo); File outputFile = new File(outputVideo); if (!outputFile.exists()) { outputFile.createNewFile(); } FileChannel source = new FileInputStream(inputFile).getChannel(); FileChannel destination = new FileOutputStream(outputFile).getChannel(); destination.transferFrom(source, 0, source.size()); // MD5 MessageDigestExtractor mde = new MessageDigestExtractor(); ToolOutput<MessageDigestExtractor.AttributeType> output = mde.extract(outputVideo); String md5sum = output.getAttribute(MessageDigestExtractor.AttributeType.MD5); // update SIP sip.addFile(format, "FILE", outputVideo, md5sum, new File(outputVideo).length()); break; } } if (inputVideo == null) { throw new TaskExecutionFailedException("Unable to find supported MQ format..."); } } catch (DataException e) { e.printStackTrace(); throw new TaskExecutionFailedException("Unable to retrieve the SIP..."); } catch (IPException e) { e.printStackTrace(); throw new TaskExecutionFailedException("Unable to retrieve MQ file from SIP..."); } catch (IOException e) { e.printStackTrace(); throw new TaskExecutionFailedException("Unable to copy MQ file..."); } catch (ToolException e) { e.printStackTrace(); throw new TaskExecutionFailedException("Unable to compute MD5 for WebM video file..."); } finally { P4DataManager.getInstance().releaseIP(sip); } }
From source file:com.symbian.driver.plugins.romflash.Activator.java
public boolean FlashRom(String romLocation) { try {/*from www. ja v a2 s . c o m*/ File rom = new File(romLocation); if (method.compareToIgnoreCase("serial") == 0) { if (!(switchOff() && switchOn())) { LOGGER.log(Level.SEVERE, "Could not reboot device, so No rom flashing."); return false; } try { Thread.sleep(10000); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish."); } File trgtTestFile = JarUtils.extractResource(Activator.class, "/resource/trgtest.exe"); if (trgtTestFile.isFile()) { ProcessBuilder ld = new ProcessBuilder(trgtTestFile.getAbsolutePath(), portNumber, rom.getCanonicalPath()); ld.directory(trgtTestFile.getParentFile()); Process pp = ld.start(); LOGGER.log(Level.INFO, "started trgtest process"); BufferedReader br = new BufferedReader(new InputStreamReader(pp.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); LOGGER.log(Level.INFO, line); } //String answer = sb.toString(); try { LOGGER.log(Level.INFO, "going to wait now for trgtest to finish"); pp.waitFor(); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "Failed to wait for trgtest.exe to finish."); } LOGGER.log(Level.INFO, "trgtest returned: " + pp.exitValue()); pp.destroy(); } else { LOGGER.log(Level.SEVERE, "Could not find trgtest.exe file."); } } else // usb rom loading { // switch the device off... switchOff(); List<File> lis1 = Arrays.asList(File.listRoots()); // get reboot plugin, and reboot the device switchOn(); // or just switch on as things may be try { Thread.sleep(10000); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish."); } File[] listRoots2 = File.listRoots(); // find the drive that made the difference!! File diff = null; for (File root : listRoots2) { if (!lis1.contains(root)) // found new drive { diff = root; break; } } File romfl = new File(diff, rom.getName()); romfl.delete(); File aCopyFrom = new File(rom.getCanonicalPath()); FileChannel lSrcChannel = new FileInputStream(aCopyFrom).getChannel(); FileChannel lDstChannel = new FileOutputStream(romfl).getChannel(); lDstChannel.transferFrom(lSrcChannel, 0, lSrcChannel.size()); lSrcChannel.close(); lDstChannel.close(); File syncFile = JarUtils.extractResource(Activator.class, "/resource/sync.exe"); if (syncFile.isFile()) { ProcessBuilder ld = new ProcessBuilder(syncFile.getAbsolutePath(), "-r", "-e", diff.toString()); ld.directory(syncFile.getParentFile()); ld.start(); // wait 10 seconds for the rom to load ... try { Thread.sleep(10000); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish."); } } else { LOGGER.log(Level.SEVERE, "Could not find sync.exe file."); } } } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "Could not flash ROM " + lIOException.getMessage()); return false; } try { Thread.sleep(10000); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish."); } return true; }
From source file:eu.prestoprime.plugin.p4.CopyTasks.java
@WfService(name = "master_file_second_copy", version = "2.0.0") public void masterFileSecondCopy(Map<String, String> sParams, Map<String, String> dParamsString, Map<String, File> dParamsFile) throws TaskExecutionFailedException { // get sipID/*from w w w.j av a 2s . co m*/ String sipID = dParamsString.get("sipID"); SIP sip = null; try { // get sip sip = P4DataManager.getInstance().getSIPByID(sipID); String inputVideo = null; // get MQ file String[] formats = sParams.get("MQformats").split(","); for (String format : formats) { List<String> videoFileList = sip.getAVMaterial(format, "FILE"); if (videoFileList.size() > 0) { inputVideo = videoFileList.get(0); String outputFolder = sParams.get("second.local.copy.folder") + File.separator + sipID; new File(outputFolder).mkdirs(); String outputVideoName = inputVideo.substring(inputVideo.lastIndexOf(File.separator) + 1); String outputVideo = outputFolder + File.separator + outputVideoName; File inputFile = new File(inputVideo); File outputFile = new File(outputVideo); if (!outputFile.exists()) { outputFile.createNewFile(); } FileChannel source = new FileInputStream(inputFile).getChannel(); FileChannel destination = new FileOutputStream(outputFile).getChannel(); destination.transferFrom(source, 0, source.size()); // MD5 MessageDigestExtractor mde = new MessageDigestExtractor(); ToolOutput<MessageDigestExtractor.AttributeType> output = mde.extract(outputVideo); String md5sum = output.getAttribute(MessageDigestExtractor.AttributeType.MD5); // update SIP sip.addFile(format, "FILE-BCK", outputVideo, md5sum, new File(outputVideo).length()); break; } } if (inputVideo == null) { throw new TaskExecutionFailedException("Unable to find supported MQ format..."); } } catch (DataException e) { e.printStackTrace(); throw new TaskExecutionFailedException("Unable to retrieve the SIP..."); } catch (IPException e) { e.printStackTrace(); throw new TaskExecutionFailedException("Unable to retrieve MQ file from SIP..."); } catch (IOException e) { e.printStackTrace(); throw new TaskExecutionFailedException("Unable to copy MQ file..."); } catch (ToolException e) { e.printStackTrace(); throw new TaskExecutionFailedException("Unable to compute MD5 for WebM video file..."); } finally { P4DataManager.getInstance().releaseIP(sip); } }
From source file:eu.europa.esig.dss.DSSUtils.java
public static void copyFile(final String path, final File sourceFile, final File destinationFile) throws IOException { final File destinationPath = new File(path); if (!destinationPath.exists()) { destinationPath.mkdirs();/*from www. jav a2 s . co m*/ destinationFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
From source file:org.python.pydev.core.REF.java
/** * Copy a file from one place to another. * /* www.j a v a 2s . co m*/ * Example from: http://www.exampledepot.com/egs/java.nio/File2File.html * * @param srcFilename the source file * @param dstFilename the destination */ public static void copyFile(String srcFilename, String dstFilename) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { // Create channel on the source srcChannel = new FileInputStream(srcFilename).getChannel(); // Create channel on the destination dstChannel = new FileOutputStream(dstFilename).getChannel(); // Copy file contents from source to destination dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { throw new RuntimeException(e); } finally { // Close the channels if (srcChannel != null) { try { srcChannel.close(); } catch (IOException e) { Log.log(e); } } if (dstChannel != null) { try { dstChannel.close(); } catch (IOException e) { Log.log(e); } } } }
From source file:display.containers.FileManager.java
public static boolean copyFile(File from, File to) throws IOException { boolean created = to.createNewFile(); if (created) { FileChannel fromChannel = null; FileChannel toChannel = null; try {/* w w w . j av a 2 s . c om*/ fromChannel = new FileInputStream(from).getChannel(); toChannel = new FileOutputStream(to).getChannel(); toChannel.transferFrom(fromChannel, 0, fromChannel.size()); // set the flags of the to the same as the from to.setReadable(from.canRead()); to.setWritable(from.canWrite()); to.setExecutable(from.canExecute()); } finally { if (fromChannel != null) { fromChannel.close(); } if (toChannel != null) { toChannel.close(); } return false; } } return created; }
From source file:de.suse.swamp.core.container.WorkflowManager.java
/** * Copy all files from "fromDir" to "toDir". * Will create the destination location if needed. * @throws Exception if source not existant or error occurs. *///from w w w.j a va 2 s . c o m private void copyDirContent(String fromDir, String toDir) throws Exception { String fs = System.getProperty("file.separator"); File[] files = new File(fromDir).listFiles(); if (files == null) { throw new FileNotFoundException("Sourcepath: " + fromDir + " not found!"); } for (int i = 0; i < files.length; i++) { File dir = new File(toDir); dir.mkdirs(); if (files[i].isFile()) { try { // Create channel on the source FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); // Create channel on the destination FileChannel dstChannel = new FileOutputStream(toDir + fs + files[i].getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { Logger.ERROR("Error during file copy: " + e.getMessage()); throw e; } } } }
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
/** * @param sourceFile/*ww w.j a v a2 s . com*/ * @param destFile * @throws IOException Copy a file to some desired location */ @SuppressWarnings("resource") public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); // previous code: destination.transferFrom(source, 0, source.size()); // to avoid infinite loops, should be: long count = 0; long size = source.size(); while ((count += destination.transferFrom(source, count, size - count)) < size) ; } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }