List of usage examples for java.nio.channels FileChannel close
public final void close() throws IOException
From source file:com.aimluck.eip.services.storage.impl.ALDefaultStorageHanlder.java
@Override public boolean copyFile(String srcRootPath, String srcDir, String srcFileName, String destRootPath, String destDir, String destFileName) { File srcPath = new File(srcRootPath + separator() + Database.getDomainName() + separator() + srcDir); if (!srcPath.exists()) { try {/*from w ww . j av a2s .co m*/ srcPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + srcPath); return false; } } File destPath = new File(destRootPath + separator() + Database.getDomainName() + separator() + destDir); if (!destPath.exists()) { try { destPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + destPath); return false; } } File from = new File(srcPath + separator() + srcFileName); File to = new File(destPath + separator() + destFileName); boolean res = true; FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(from).getChannel(); destChannel = new FileOutputStream(to).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (Exception ex) { logger.error("ALDefaultStorageHanlder.copyFile", ex); res = false; } finally { if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { logger.error("ALDefaultStorageHanlder.copyFile", ex); res = false; } } if (srcChannel != null) { try { srcChannel.close(); } catch (IOException ex) { logger.error("ALDefaultStorageHanlder.copyFile", ex); res = false; } } } return res; }
From source file:org.kie.commons.java.nio.fs.file.SimpleFileSystemProviderTest.java
@Test public void checkNewFileChannel() throws IOException { final File temp = File.createTempFile("foo", "bar"); final SimpleFileSystemProvider fsProvider = new SimpleFileSystemProvider(); final Path path = GeneralPathImpl.newFromFile(fsProvider.getFileSystem(URI.create("file:///")), temp); final FileChannel stream = fsProvider.newFileChannel(path, null); assertThat(stream).isNotNull();/* w w w. j a v a2 s. c o m*/ stream.close(); }
From source file:com.aimluck.eip.services.storage.impl.ALDefaultStorageHandler.java
@Override public boolean copyFile(String srcRootPath, String srcDir, String srcFileName, String destRootPath, String destDir, String destFileName) { File srcPath = new File( getAbsolutePath(srcRootPath) + separator() + Database.getDomainName() + separator() + srcDir); if (!srcPath.exists()) { try {//from w w w . j a v a 2 s . com srcPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + srcPath); return false; } } File destPath = new File( getAbsolutePath(destRootPath) + separator() + Database.getDomainName() + separator() + destDir); if (!destPath.exists()) { try { destPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + destPath); return false; } } File from = new File(srcPath + separator() + srcFileName); File to = new File(destPath + separator() + destFileName); boolean res = true; FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(from).getChannel(); destChannel = new FileOutputStream(to).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (Exception ex) { logger.error("ALDefaultStorageHandler.copyFile", ex); res = false; } finally { if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { logger.error("ALDefaultStorageHandler.copyFile", ex); res = false; } } if (srcChannel != null) { try { srcChannel.close(); } catch (IOException ex) { logger.error("ALDefaultStorageHandler.copyFile", ex); res = false; } } } return res; }
From source file:org.apache.solr.core.CoreContainer.java
/** Copies a src file to a dest file: * used to circumvent the platform discrepancies regarding renaming files. */// w w w . jav a 2s . c o m public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); // do the file copy 32Mb at a time final int MB32 = 32 * 1024 * 1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch (IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch (IOException xio) { } if (fos != null) try { fos.close(); fos = null; } catch (IOException xio) { } if (fcin != null && fcin.isOpen()) try { fcin.close(); fcin = null; } catch (IOException xio) { } if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch (IOException xio) { } } if (xforward != null) { throw xforward; } }
From source file:org.cloudata.core.commitlog.CommitLogServer.java
public int readLastLogFromMarkedPosition(String dirName) { File logFile = getLogFile(dirName); File indexFile = getLogIndexFile(dirName); FileChannel ch = null;// w ww . jav a 2s . c o m try { long index = 0; if (logFile.exists() == false) { LOG.warn("A directory [" + dirName + "] or log file does not exist"); return -1; } else if (indexFile.exists()) { FileChannel indexChannel = new FileInputStream(indexFile).getChannel(); index = CommitLogFileChannel.readLastIndex(indexChannel); LOG.info("index of dir [" + dirName + "] : " + index); indexChannel.close(); } FileInputStream in = new FileInputStream(logFile); ch = in.getChannel(); ch.position(index); } catch (IOException e) { LOG.error("Fail to read logs", e); return -1; } return startFileTransferChannel(dirName, ch); }
From source file:sos.scheduler.editor.app.WebDavDialogListener.java
public void deleteProfile(String profilename) throws Exception { try {//from www . j av a 2 s. c o m setCurrProfileName(profilename); //java.util.Properties profile = getCurrProfile(); String filename = configFile; byte[] b = getBytesFromFile(new File(filename)); String s = new String(b); //System.out.println(s); int pos1 = s.indexOf("[" + PREFIX + " " + profilename + "]"); int pos2 = s.indexOf("[", pos1 + 1); if (pos1 == -1) { //System.out.println("profile nicht gefunden"); pos1 = s.length(); pos2 = -1; return; } if (pos2 == -1) pos2 = s.length(); String s2 = s.substring(0, pos1) + s.substring(pos2); java.nio.ByteBuffer bbuf = java.nio.ByteBuffer.wrap(s2.getBytes()); java.io.File file = new java.io.File(filename); boolean append = false; java.nio.channels.FileChannel wChannel = new java.io.FileOutputStream(file, append).getChannel(); wChannel.write(bbuf); wChannel.close(); } catch (java.io.IOException e) { try { new ErrorLog("error in " + sos.util.SOSClassUtil.getMethodName() + " ; could not delete profile=" + profilename, e); } catch (Exception ee) { //tu nichts } hasError = true; throw new Exception(e.getMessage()); } finally { cboConnectname.setItems(getProfileNames()); cboConnectname.setText(currProfileName); txtURL.setText(currProfile.getProperty("url")); } }
From source file:org.oscarehr.document.web.ManageDocumentAction.java
public File createCacheVersion(Document d, int pageNum) throws Exception { File documentCacheDir = new File(EDocUtil.getCacheDirectory()); File file = new File(EDocUtil.getDocumentPath(d.getDocfilename())); RandomAccessFile raf = new RandomAccessFile(file, "r"); FileChannel channel = raf.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); PDFFile pdffile = new PDFFile(buf); if (raf != null) raf.close();//from ww w. j a v a 2 s .c o m if (channel != null) channel.close(); // draw the first page to an image PDFPage ppage = pdffile.getPage(pageNum); log.debug("WIDTH " + (int) ppage.getBBox().getWidth() + " height " + (int) ppage.getBBox().getHeight()); // get the width and height for the doc at the default zoom Rectangle rect = new Rectangle(0, 0, (int) ppage.getBBox().getWidth(), (int) ppage.getBBox().getHeight()); log.debug("generate the image"); Image img = ppage.getImage(rect.width, rect.height, // width & height rect, // clip rect null, // null for the ImageObserver true, // fill background with white true // block until drawing is done ); log.debug("about to Print to stream"); File outfile = new File(documentCacheDir, d.getDocfilename() + "_" + pageNum + ".png"); OutputStream outs = null; try { outs = new FileOutputStream(outfile); RenderedImage rendImage = (RenderedImage) img; ImageIO.write(rendImage, "png", outs); outs.flush(); } finally { if (outs != null) outs.close(); } return outfile; }
From source file:org.alfresco.repo.content.AbstractContentReader.java
/** * {@inheritDoc}/* w ww . ja v a 2 s. c o m*/ */ public FileChannel getFileChannel() throws ContentIOException { /* * Where the underlying support is not present for this method, a temporary * file will be used as a substitute. When the write is complete, the * results are copied directly to the underlying channel. */ // get the underlying implementation's best readable channel channel = getReadableChannel(); // now use this channel if it can provide the random access, otherwise spoof it FileChannel clientFileChannel = null; if (channel instanceof FileChannel) { // all the support is provided by the underlying implementation clientFileChannel = (FileChannel) channel; // debug if (logger.isDebugEnabled()) { logger.debug("Content reader provided direct support for FileChannel: \n" + " reader: " + this); } } else { // No random access support is provided by the implementation. // Spoof it by providing a 2-stage read from a temp file File tempFile = TempFileProvider.createTempFile("random_read_spoof_", ".bin"); FileContentWriter spoofWriter = new FileContentWriter(tempFile); // pull the content in from the underlying channel FileChannel spoofWriterChannel = spoofWriter.getFileChannel(false); try { long spoofFileSize = this.getSize(); spoofWriterChannel.transferFrom(channel, 0, spoofFileSize); } catch (IOException e) { throw new ContentIOException( "Failed to copy from permanent channel to spoofed temporary channel: \n" + " reader: " + this + "\n" + " temp: " + spoofWriter, e); } finally { try { spoofWriterChannel.close(); } catch (IOException e) { } } // get a reader onto the spoofed content final ContentReader spoofReader = spoofWriter.getReader(); // Attach a listener // - ensure that the close call gets propogated to the underlying channel ContentStreamListener spoofListener = new ContentStreamListener() { public void contentStreamClosed() throws ContentIOException { try { channel.close(); } catch (IOException e) { throw new ContentIOException("Failed to close underlying channel", e); } } }; spoofReader.addListener(spoofListener); // we now have the spoofed up channel that the client can work with clientFileChannel = spoofReader.getFileChannel(); // debug if (logger.isDebugEnabled()) { logger.debug("Content writer provided indirect support for FileChannel: \n" + " writer: " + this + "\n" + " temp writer: " + spoofWriter); } } // the file is now available for random access return clientFileChannel; }
From source file:sos.scheduler.editor.app.WebDavDialogListener.java
public void saveProfile(boolean savePassword) { try {/* www.j av a 2 s . c o m*/ java.util.Properties profile = getCurrProfile(); String filename = configFile; String profilename = currProfileName; byte[] b = getBytesFromFile(new File(filename)); String s = new String(b); //System.out.println(s); int pos1 = s.indexOf("[" + PREFIX + profilename + "]"); int pos2 = s.indexOf("[", pos1 + 1); if (pos1 == -1) { //System.out.println("profile nicht gefunden"); pos1 = s.length(); pos2 = -1; } if (pos2 == -1) pos2 = s.length(); String s2 = s.substring(0, pos1); s2 = s2 + "[" + PREFIX + profilename + "]\n\n"; s2 = s2 + "url=" + sosString.parseToString(profile.get("url")) + "\n"; s2 = s2 + "user=" + sosString.parseToString(profile.get("user")) + "\n"; try { if (savePassword && sosString.parseToString(profile.get("password")).length() > 0) { String pass = String.valueOf(SOSUniqueID.get()); Options.setProperty("profile.timestamp." + profilename, pass); Options.saveProperties(); if (pass.length() > 8) { pass = pass.substring(pass.length() - 8); } String encrypt = SOSCrypt.encrypt(pass, sosString.parseToString(profile.get("password"))); s2 = s2 + "password=" + encrypt + "\n"; profile.put("password", encrypt); this.password = encrypt; getProfiles().put(profilename, profile); } } catch (Exception e) { new ErrorLog("error in " + sos.util.SOSClassUtil.getMethodName() + " ; ..could not encrypt.", e); throw e; } s2 = s2 + "localdirectory=" + sosString.parseToString(profile.get("localdirectory")) + "\n"; s2 = s2 + "save_password=" + sosString.parseToString(profile.get("save_password")) + "\n"; s2 = s2 + "protocol=" + sosString.parseToString(profile.get("protocol")) + "\n"; s2 = s2 + "use_proxy=" + sosString.parseToString(profile.get("use_proxy")) + "\n"; s2 = s2 + "proxy_server=" + sosString.parseToString(profile.get("proxy_server")) + "\n"; s2 = s2 + "proxy_port=" + sosString.parseToString(profile.get("proxy_port")) + "\n"; s2 = s2 + "\n\n"; s2 = s2 + s.substring(pos2); // System.out.println("+++++++++++++++++++++++++++++++++++"); // System.out.println(s2); // System.out.println("+++++++++++++++++++++++++++++++++++"); java.nio.ByteBuffer bbuf = java.nio.ByteBuffer.wrap(s2.getBytes()); java.io.File file = new java.io.File(filename); boolean append = false; java.nio.channels.FileChannel wChannel = new java.io.FileOutputStream(file, append).getChannel(); wChannel.write(bbuf); wChannel.close(); /*} catch (java.io.IOException e) { hasError = true; MainWindow.message("could not save configurations File: " + configFile + ": cause:\n" + e.getMessage(), SWT.ICON_WARNING); */ } catch (Exception e) { try { new ErrorLog("error in " + sos.util.SOSClassUtil.getMethodName() + " ; could not save configurations File: " + configFile, e); } catch (Exception ee) { //tu nichts } hasError = true; MainWindow.message("could not save configurations File: " + configFile + ": cause:\n" + e.getMessage(), SWT.ICON_WARNING); } finally { cboConnectname.setItems(getProfileNames()); cboConnectname.setText(currProfileName); txtURL.setText(currProfile.getProperty("url")); } }
From source file:com.intervigil.micdroid.MainActivity.java
@Override public void onExport(Recording r) { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Log.w(TAG, "onExport: External media is not available"); Toast.makeText(mContext, R.string.recording_options_export_external_media_unavailable, Toast.LENGTH_SHORT).show(); return;//from w ww . java2s . c o m } File externalMusicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); if (!externalMusicDir.exists() && !externalMusicDir.mkdirs()) { Log.e(TAG, "onExport: Failed to create external music directory"); Toast.makeText(mContext, R.string.recording_options_export_external_music_dir_unavailable, Toast.LENGTH_SHORT).show(); return; } File exported = new File(externalMusicDir, r.getName()); FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = mContext.openFileInput(r.getName()).getChannel(); dstChannel = new FileOutputStream(exported).getChannel(); srcChannel.transferTo(0, srcChannel.size(), dstChannel); Toast.makeText(mContext, R.string.recording_options_export_complete, Toast.LENGTH_SHORT).show(); } catch (IOException e) { Log.e(TAG, "onExport: Failed to export file: " + r.getName()); e.printStackTrace(); Toast.makeText(mContext, R.string.recording_options_export_copy_error, Toast.LENGTH_SHORT).show(); } finally { try { if (srcChannel != null) { srcChannel.close(); } if (dstChannel != null) { dstChannel.close(); } } catch (IOException e) { // Do nothing } } }