List of usage examples for java.nio.channels FileChannel close
public final void close() throws IOException
From source file:org.gnucash.android.export.ExportAsyncTask.java
/** * Moves 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 moved. *//*from w ww.j ava 2s. co m*/ public void moveFile(String src, String dst) throws IOException { File srcFile = new File(src); File dstFile = new File(dst); FileChannel inChannel = new FileInputStream(srcFile).getChannel(); FileChannel outChannel = new FileOutputStream(dstFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); outChannel.close(); } srcFile.delete(); }
From source file:com.sds.acube.ndisc.mts.xserver.util.XNDiscUtils.java
/** * ? // ww w .j av a2s . co m * * @param nFile * NFile * @param bForwardMedia * ? ? * @param bForce * * @throws Exception */ public static void copyNFile(NFile[] nFile, boolean bForwardMedia, boolean bForce) throws Exception { FileChannel srcChannel = null; FileChannel dstChannel = null; String srcFile = null; String dstFile = null; try { for (int i = 0; i < nFile.length; i++) { if (false == bForce && XNDiscConfig.STAT_NONE.equals(nFile[i].getStatType())) { continue; } else { if (bForwardMedia) { srcFile = nFile[i].getTmpPath(); dstFile = nFile[i].getStoragePath(); } else { srcFile = nFile[i].getStoragePath(); dstFile = nFile[i].getTmpPath(); } srcChannel = new FileInputStream(srcFile).getChannel(); dstChannel = new FileOutputStream(dstFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); if (bForwardMedia) { new File(srcFile).delete(); } } } } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (null != srcChannel && srcChannel.isOpen()) { srcChannel.close(); } if (null != dstChannel && dstChannel.isOpen()) { dstChannel.close(); } } }
From source file:org.alfresco.filesys.repo.CommandExecutorImpl.java
/** * @param sess SrvSession//from ww w .jav a 2 s . c o m * @param tree TreeConnection * @param command Command * @param result Object * @return Object * @throws IOException */ private Object executeInternal(SrvSession sess, TreeConnection tree, Command command, Object result) throws IOException { FileFilterMode.setClient(ClientHelper.getClient(sess)); try { if (command instanceof CompoundCommand) { Object ret = null; logger.debug("compound command received"); CompoundCommand x = (CompoundCommand) command; for (Command compoundPart : x.getCommands()) { logger.debug("running part of compound command"); Object val = executeInternal(sess, tree, compoundPart, result); if (val != null) { // Return the value from the last command. ret = val; } } return ret; } else if (command instanceof CreateFileCommand) { logger.debug("create file command"); CreateFileCommand create = (CreateFileCommand) command; return repositoryDiskInterface.createFile(create.getRootNode(), create.getPath(), create.getAllocationSize(), create.isHidden()); } else if (command instanceof RestoreFileCommand) { logger.debug("restore file command"); RestoreFileCommand restore = (RestoreFileCommand) command; return repositoryDiskInterface.restoreFile(sess, tree, restore.getRootNode(), restore.getPath(), restore.getAllocationSize(), restore.getOriginalNodeRef()); } else if (command instanceof DeleteFileCommand) { logger.debug("delete file command"); DeleteFileCommand delete = (DeleteFileCommand) command; return repositoryDiskInterface.deleteFile2(sess, tree, delete.getRootNode(), delete.getPath()); } else if (command instanceof OpenFileCommand) { logger.debug("open file command"); OpenFileCommand o = (OpenFileCommand) command; OpenFileMode mode = o.getMode(); return repositoryDiskInterface.openFile(sess, tree, o.getRootNodeRef(), o.getPath(), mode, o.isTruncate()); } else if (command instanceof CloseFileCommand) { logger.debug("close file command"); CloseFileCommand c = (CloseFileCommand) command; return repositoryDiskInterface.closeFile(tree, c.getRootNodeRef(), c.getPath(), c.getNetworkFile()); } else if (command instanceof ReduceQuotaCommand) { logger.debug("reduceQuota file command"); ReduceQuotaCommand r = (ReduceQuotaCommand) command; repositoryDiskInterface.reduceQuota(sess, tree, r.getNetworkFile()); } else if (command instanceof RenameFileCommand) { logger.debug("rename command"); RenameFileCommand rename = (RenameFileCommand) command; repositoryDiskInterface.renameFile(rename.getRootNode(), rename.getFromPath(), rename.getToPath(), rename.isSoft(), false); } else if (command instanceof MoveFileCommand) { logger.debug("move command"); MoveFileCommand move = (MoveFileCommand) command; repositoryDiskInterface.renameFile(move.getRootNode(), move.getFromPath(), move.getToPath(), false, move.isMoveAsSystem()); } else if (command instanceof CopyContentCommand) { if (logger.isDebugEnabled()) { logger.debug("Copy content command - copy content"); } CopyContentCommand copy = (CopyContentCommand) command; repositoryDiskInterface.copyContent(copy.getRootNode(), copy.getFromPath(), copy.getToPath()); } else if (command instanceof DoNothingCommand) { if (logger.isDebugEnabled()) { logger.debug("Do Nothing Command - doing nothing"); } } else if (command instanceof ResultCallback) { if (logger.isDebugEnabled()) { logger.debug("Result Callback"); } ResultCallback callback = (ResultCallback) command; callback.execute(result); } else if (command instanceof RemoveTempFileCommand) { RemoveTempFileCommand r = (RemoveTempFileCommand) command; if (logger.isDebugEnabled()) { logger.debug("Remove Temp File:" + r.getNetworkFile()); } File file = r.getNetworkFile().getFile(); boolean isDeleted = file.delete(); if (!isDeleted) { logger.debug("unable to delete temp file:" + r.getNetworkFile() + ", closed=" + r.getNetworkFile().isClosed()); /* * Unable to delete temporary file * Could be a bug with the file handle not being closed, but yourkit does not * find anything awry. * There are reported Windows JVM bugs such as 4715154 ... */ FileOutputStream fos = new FileOutputStream(file); FileChannel outChan = null; try { outChan = fos.getChannel(); outChan.truncate(0); } catch (IOException e) { logger.debug("unable to clean up file", e); } finally { if (outChan != null) { try { outChan.close(); } catch (IOException e) { } } fos.close(); } } } else if (command instanceof ReturnValueCommand) { ReturnValueCommand r = (ReturnValueCommand) command; if (logger.isDebugEnabled()) { logger.debug("Return value"); } return r.getReturnValue(); } else if (command instanceof RemoveNoContentFileOnError) { RemoveNoContentFileOnError r = (RemoveNoContentFileOnError) command; if (logger.isDebugEnabled()) { logger.debug("Remove no content file on error"); } repositoryDiskInterface.deleteEmptyFile(r.getRootNodeRef(), r.getPath()); } } finally { FileFilterMode.clearClient(); } return null; }
From source file:com.vmware.photon.controller.deployer.deployengine.DockerProvisioner.java
public void createImageFromTar(String filePath, String imageName) { if (StringUtils.isBlank(imageName)) { throw new IllegalArgumentException("imageName field cannot be null or blank"); }// w ww . j a va 2 s .c o m if (StringUtils.isBlank(filePath)) { throw new IllegalArgumentException("filePath field cannot be null or blank"); } File tarFile = new File(filePath); try (FileInputStream fileInputStream = new FileInputStream(tarFile)) { FileChannel in = fileInputStream.getChannel(); String endpoint = getImageLoadEndpoint(); URL url = new URL(endpoint); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "application/json"); connection.setDoOutput(true); WritableByteChannel out = Channels.newChannel(connection.getOutputStream()); in.transferTo(0, tarFile.length(), out); in.close(); out.close(); int responseCode = connection.getResponseCode(); if (!String.valueOf(responseCode).startsWith("2")) { throw new RuntimeException( "Docker Endpoint cannot load image from tar. Failed with response code " + responseCode); } } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.opennms.features.newts.converter.rrd.converter.JRobinConverter.java
public boolean moveFileSafely(final File in, final File out) throws IOException { FileInputStream fis = null;//w w w . j a va 2 s . c o m FileOutputStream fos = null; FileChannel inChannel = null; FileChannel outChannel = null; final File tempOut = File.createTempFile("move", ".tmp"); try { fis = new FileInputStream(in); fos = new FileOutputStream(tempOut); inChannel = fis.getChannel(); outChannel = fos.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", inChannel); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", outChannel); } try { if (fis != null) fis.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fis); } try { if (fos != null) fos.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fos); } } out.delete(); if (!out.exists()) { tempOut.renameTo(out); return in.delete(); } return false; }
From source file:org.wso2.carbon.mediation.library.service.upload.LibraryUploader.java
private void writeResource(DataHandler dataHandler, String tempDestPath, String destPath, String fileName) throws IOException { File tempDestFile = new File(tempDestPath, fileName); FileChannel out = null; FileChannel in = null;// w w w . j a v a 2s . c o m FileOutputStream fos = null; try { fos = new FileOutputStream(tempDestFile); dataHandler.writeTo(fos); fos.flush(); /* File stream is copied to a temp directory in order handle hot deployment issue occurred in windows */ dataHandler.writeTo(fos); out = new FileOutputStream(destPath + File.separator + fileName).getChannel(); in = new FileInputStream(tempDestFile).getChannel(); out.write(in.map(FileChannel.MapMode.READ_ONLY, 0, in.size())); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { log.warn("Can't close file streams.", e); } try { if (in != null) { in.close(); } } catch (IOException e) { log.warn("Can't close file streams.", e); } try { if (fos != null) { fos.close(); } } catch (IOException e) { log.warn("Can't close file streams.", e); } } if (!tempDestFile.delete()) { if (log.isDebugEnabled()) { log.debug("temp file: " + tempDestFile.getAbsolutePath() + " deletion failed, scheduled deletion on server exit."); } tempDestFile.deleteOnExit(); } }
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 ava 2 s . co 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:org.wso2.appserver.integration.tests.config.EnvironmentVariableReadTestCase.java
public void applyConfiguration(File sourceFile, File targetFile) throws IOException { FileChannel source = null; FileChannel destination = null; if (!targetFile.exists() && !targetFile.createNewFile()) { throw new IOException("File " + targetFile + "creation fails"); }/*from ww w .j a va 2s . co m*/ source = (new FileInputStream(sourceFile)).getChannel(); destination = (new FileOutputStream(targetFile)).getChannel(); destination.transferFrom(source, 0L, source.size()); if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
From source file:tachyon.command.TFsShell.java
private int copyPath(File src, TachyonFS tachyonClient, String dstPath) throws IOException { if (!src.isDirectory()) { int fileId = tachyonClient.createFile(dstPath); if (fileId == -1) { return -1; }//from w w w. j a v a 2 s . c om TachyonFile tFile = tachyonClient.getFile(fileId); OutStream os = tFile.getOutStream(WriteType.CACHE_THROUGH); FileInputStream in = new FileInputStream(src); FileChannel channel = in.getChannel(); ByteBuffer buf = ByteBuffer.allocate(Constants.KB); while (channel.read(buf) != -1) { buf.flip(); os.write(buf.array(), 0, buf.limit()); } os.close(); channel.close(); in.close(); return 0; } else { tachyonClient.mkdir(dstPath); for (String file : src.list()) { String newPath = FilenameUtils.concat(dstPath, file); File srcFile = new File(src, file); if (copyPath(srcFile, tachyonClient, newPath) == -1) { return -1; } } } return 0; }