List of usage examples for java.nio.channels FileChannel size
public abstract long size() throws IOException;
From source file:com.stimulus.archiva.store.MessageStore.java
public void copyEmail(File source, File dest) throws MessageStoreException { logger.debug("copyEmail()"); FileChannel in = null, out = null; try {//w w w .j av a2 s . co m in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { throw new MessageStoreException("failed to copy email {src='" + source + "=',dest='" + dest + "'", e, logger); } finally { if (in != null) try { in.close(); } catch (Exception e) { } ; if (out != null) try { out.close(); } catch (Exception e) { } ; } }
From source file:com.aipo.social.opensocial.spi.AipoStorageService.java
@Override public boolean copyFile(String srcRootPath, String srcDir, String srcFileName, String destRootPath, String destDir, String destFileName, SecurityToken paramSecurityToken) throws ProtocolException { File srcPath = new File( getAbsolutePath(srcRootPath) + separator() + Database.getDomainName() + separator() + srcDir); if (!srcPath.exists()) { try {//from w w w .j a va 2 s . com srcPath.mkdirs(); } catch (Exception e) { return false; } } File destPath = new File( getAbsolutePath(destRootPath) + separator() + Database.getDomainName() + separator() + destDir); if (!destPath.exists()) { try { destPath.mkdirs(); } catch (Exception e) { 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) { res = false; } finally { if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { res = false; } } if (srcChannel != null) { try { srcChannel.close(); } catch (IOException ex) { res = false; } } } return res; }
From source file:de.tobiasroeser.maven.featurebuilder.FeatureBuilder.java
private void copyJarsAsBundles(final List<Bundle> bundles, final String copyJarsAsBundlesTo) { final File dir = new File(copyJarsAsBundlesTo); if (dir.exists()) { if (!dir.isDirectory()) { log.error(dir.getAbsolutePath() + " is not a directory."); return; }// w w w. j av a 2 s . c o m } else { dir.mkdirs(); } log.info("Copying " + bundles.size() + " bundles into: " + dir.getAbsolutePath()); for (final Bundle bundle : bundles) { final File target = new File(dir, bundle.getSymbolicName() + "_" + bundle.getVersion() + ".jar"); FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(bundle.getJarLocation()).getChannel(); out = new FileOutputStream(target).getChannel(); // According to // http://www.rgagnon.com/javadetails/java-0064.html // we cannot copy files greater than 64 MB. // magic number for Windows, 64Mb - 32Kb) final int maxCount = (64 * 1024 * 1024) - (32 * 1024); final long size = in.size(); long position = 0; while (position < size) { position += in.transferTo(position, maxCount, out); } } catch (final IOException e) { log.error("Error whily copying '" + bundle.getJarLocation().getAbsolutePath() + "' to '" + target.getAbsolutePath() + "'", e); return; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (final IOException e) { throw new RuntimeException("Could not recover from error.", e); } } } }
From source file:com.stfalcon.contentmanager.ContentManager.java
private void handleMediaContent(final Intent data) { pickContentListener.onStartContentLoading(); new Thread(new Runnable() { public void run() { try { Uri contentVideoUri = data.getData(); FileInputStream in = (FileInputStream) activity.getContentResolver() .openInputStream(contentVideoUri); if (targetFile == null) { targetFile = createFile(savedContent); }//from w ww .j a va 2 s. c om FileOutputStream out = new FileOutputStream(targetFile); FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); in.close(); out.close(); handler.post(new Runnable() { @Override public void run() { pickContentListener.onContentLoaded(Uri.fromFile(targetFile), savedContent.toString()); } }); } catch (final Exception e) { handler.post(new Runnable() { @Override public void run() { pickContentListener.onError(e.getMessage()); } }); } } }).start(); }
From source file:eu.planets_project.tb.impl.data.util.DataHandlerImpl.java
public File copyLocalFileAsTempFileInExternallyAccessableDir(String localFileRef) throws IOException { //get a temporary file log.debug("copyLocalFileAsTempFileInExternallyAccessableDir"); File f = this.createTempFileInExternallyAccessableDir(); //copying one file to another with FileChannel //@see http://www.exampledepot.com/egs/java.nio/File2File.html FileChannel srcChannel = new FileInputStream(localFileRef).getChannel(); FileChannel dstChannel = new FileOutputStream(f).getChannel(); log.debug("before transferring via FileChannel from src-inputStream: " + localFileRef + " to dest-outputStream: " + f.getAbsolutePath()); // Copy file contents from source to destination dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); //Close the channels srcChannel.close();//from w w w . ja v a2 s . c o m dstChannel.close(); log.debug("copyLocalFileAsTempFileInExternallyAccessableDir returning: " + f.getAbsolutePath()); return f; }
From source file:org.apache.cordova.core.FileUtils.java
/** * Moved this code into it's own method so moveTo could use it when the move is across file systems *///from w ww . j a v a2 s . co m private void copyAction(File srcFile, File destFile) throws FileNotFoundException, IOException { FileInputStream istream = new FileInputStream(srcFile); FileOutputStream ostream = new FileOutputStream(destFile); FileChannel input = istream.getChannel(); FileChannel output = ostream.getChannel(); try { input.transferTo(0, input.size(), output); } finally { istream.close(); ostream.close(); input.close(); output.close(); } }
From source file:com.MustacheMonitor.MustacheMonitor.FileUtils.java
/** * Copy a file//w w w . ja v a 2s .co m * * @param srcFile file to be copied * @param destFile destination to be copied to * @return a FileEntry object * @throws IOException * @throws InvalidModificationException * @throws JSONException */ private JSONObject copyFile(File srcFile, File destFile) throws IOException, InvalidModificationException, JSONException { // Renaming a file to an existing directory should fail if (destFile.exists() && destFile.isDirectory()) { throw new InvalidModificationException("Can't rename a file to a directory"); } FileChannel input = new FileInputStream(srcFile).getChannel(); FileChannel output = new FileOutputStream(destFile).getChannel(); input.transferTo(0, input.size(), output); input.close(); output.close(); /* if (srcFile.length() != destFile.length()) { return false; } */ return getEntry(destFile); }
From source file:org.rhq.plugins.jslee.JainSleeServerComponent.java
private void copyFile(File sourceFile, File destFile) throws IOException { if (log.isDebugEnabled()) { log.debug("CopyFile : Source[" + sourceFile.getAbsolutePath() + "] Dest[" + destFile.getAbsolutePath() + "]"); }/*from ww w.j a v a 2 s . c o m*/ if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
From source file:org.red5.io.flv.FLVReader.java
/** * Creates FLV reader from file channel. * * @param channel/*from w ww. j a v a 2 s .c om*/ * @throws IOException on error */ public FLVReader(FileChannel channel) throws IOException { if (null == channel) { log.warn("Reader was passed a null channel"); log.debug("{}", org.apache.commons.lang.builder.ToStringBuilder.reflectionToString(this)); } if (!channel.isOpen()) { log.warn("Reader was passed a closed channel"); return; } this.channel = channel; channelSize = channel.size(); //log.debug("Channel size: {}", channelSize); if (channel.position() > 0) { log.debug("Channel position: {}", channel.position()); channel.position(0); } fillBuffer(); postInitialize(); }
From source file:fr.paris.lutece.plugins.directory.web.action.ExportDirectoryAction.java
/** * {@inheritDoc}//from w w w . j ava2 s . c o m */ @Override public IPluginActionResult process(HttpServletRequest request, HttpServletResponse response, AdminUser adminUser, DirectoryAdminSearchFields searchFields) throws AccessDeniedException { DefaultPluginActionResult result = new DefaultPluginActionResult(); String strIdDirectory = request.getParameter(PARAMETER_ID_DIRECTORY); int nIdDirectory = DirectoryUtils.convertStringToInt(strIdDirectory); Directory directory = DirectoryHome.findByPrimaryKey(nIdDirectory, getPlugin()); String strIdDirectoryXsl = request.getParameter(PARAMETER_ID_DIRECTORY_XSL); int nIdDirectoryXsl = DirectoryUtils.convertStringToInt(strIdDirectoryXsl); WorkflowService workflowService = WorkflowService.getInstance(); boolean bWorkflowServiceEnable = workflowService.isAvailable(); String strShotExportFinalOutPut = null; DirectoryXsl directoryXsl = DirectoryXslHome.findByPrimaryKey(nIdDirectoryXsl, getPlugin()); // ----------------------------------------------------------------------- if ((directory == null) || (directoryXsl == null) || !RBACService.isAuthorized(Directory.RESOURCE_TYPE, strIdDirectory, DirectoryResourceIdService.PERMISSION_MANAGE_RECORD, adminUser)) { throw new AccessDeniedException( I18nService.getLocalizedString(MESSAGE_ACCESS_DENIED, request.getLocale())); } String strFileExtension = directoryXsl.getExtension(); String strFileName = directory.getTitle() + "." + strFileExtension; strFileName = UploadUtil.cleanFileName(strFileName); boolean bIsCsvExport = strFileExtension.equals(EXPORT_CSV_EXT); boolean bDisplayDateCreation = directory.isDateShownInExport(); boolean bDisplayDateModification = directory.isDateModificationShownInExport(); List<Integer> listResultRecordId = new ArrayList<Integer>(); if (request.getParameter(PARAMETER_BUTTON_EXPORT_SEARCH) != null) { String[] selectedRecords = request.getParameterValues(PARAMETER_SELECTED_RECORD); List<String> listSelectedRecords; if (selectedRecords != null) { listSelectedRecords = Arrays.asList(selectedRecords); if ((listSelectedRecords != null) && (listSelectedRecords.size() > 0)) { for (String strRecordId : listSelectedRecords) { listResultRecordId.add(Integer.parseInt(strRecordId)); } } } else { // sort order and sort entry are not needed in export listResultRecordId = DirectoryUtils.getListResults(request, directory, bWorkflowServiceEnable, true, null, RecordFieldFilter.ORDER_NONE, searchFields, adminUser, adminUser.getLocale()); } } else { // sort order and sort entry are not needed in export listResultRecordId = DirectoryUtils.getListResults(request, directory, bWorkflowServiceEnable, false, null, RecordFieldFilter.ORDER_NONE, searchFields, adminUser, adminUser.getLocale()); } EntryFilter entryFilter = new EntryFilter(); entryFilter.setIdDirectory(directory.getIdDirectory()); entryFilter.setIsGroup(EntryFilter.FILTER_FALSE); entryFilter.setIsComment(EntryFilter.FILTER_FALSE); entryFilter.setIsShownInExport(EntryFilter.FILTER_TRUE); List<IEntry> listEntryResultSearch = EntryHome.getEntryList(entryFilter, getPlugin()); Map<Integer, Field> hashFields = DirectoryUtils.getMapFieldsOfListEntry(listEntryResultSearch, getPlugin()); StringBuffer strBufferListRecordXml = null; java.io.File tmpFile = null; BufferedWriter bufferedWriter = null; OutputStreamWriter outputStreamWriter = null; File fileTemplate = null; String strFileOutPut = DirectoryUtils.EMPTY_STRING; if (directoryXsl.getFile() != null) { fileTemplate = FileHome.findByPrimaryKey(directoryXsl.getFile().getIdFile(), getPlugin()); } XmlTransformerService xmlTransformerService = null; PhysicalFile physicalFile = null; String strXslId = null; if ((fileTemplate != null) && (fileTemplate.getPhysicalFile() != null)) { fileTemplate.setPhysicalFile(PhysicalFileHome .findByPrimaryKey(fileTemplate.getPhysicalFile().getIdPhysicalFile(), getPlugin())); xmlTransformerService = new XmlTransformerService(); physicalFile = fileTemplate.getPhysicalFile(); strXslId = XSL_UNIQUE_PREFIX_ID + physicalFile.getIdPhysicalFile(); } int nSize = listResultRecordId.size(); boolean bIsBigExport = (nSize > EXPORT_RECORD_STEP); // Encoding export String strEncoding = StringUtils.EMPTY; if (bIsCsvExport) { strEncoding = DirectoryParameterService.getService().getExportCSVEncoding(); } else { strEncoding = DirectoryParameterService.getService().getExportXMLEncoding(); } if (bIsBigExport) { try { String strPath = AppPathService.getWebAppPath() + AppPropertiesService.getProperty(PROPERTY_PATH_TMP); java.io.File tmpDir = new java.io.File(strPath); tmpFile = java.io.File.createTempFile(EXPORT_TMPFILE_PREFIX, EXPORT_TMPFILE_SUFIX, tmpDir); } catch (IOException e) { AppLogService.error("Unable to create temp file in webapp tmp dir"); try { tmpFile = java.io.File.createTempFile(EXPORT_TMPFILE_PREFIX, EXPORT_TMPFILE_SUFIX); } catch (IOException e1) { AppLogService.error(e1); } } try { tmpFile.deleteOnExit(); outputStreamWriter = new OutputStreamWriter(new FileOutputStream(tmpFile), strEncoding); bufferedWriter = new BufferedWriter(outputStreamWriter); } catch (IOException e) { AppLogService.error(e); } } Plugin plugin = this.getPlugin(); Locale locale = request.getLocale(); // --------------------------------------------------------------------- StringBuffer strBufferListEntryXml = new StringBuffer(); if (bDisplayDateCreation && bIsCsvExport) { Map<String, String> model = new HashMap<String, String>(); model.put(Entry.ATTRIBUTE_ENTRY_ID, "0"); XmlUtil.beginElement(strBufferListEntryXml, Entry.TAG_ENTRY, model); String strDateCreation = I18nService.getLocalizedString(PROPERTY_ENTRY_TYPE_DATE_CREATION_TITLE, locale); XmlUtil.addElementHtml(strBufferListEntryXml, Entry.TAG_TITLE, strDateCreation); XmlUtil.endElement(strBufferListEntryXml, Entry.TAG_ENTRY); } if (bDisplayDateModification && bIsCsvExport) { Map<String, String> model = new HashMap<String, String>(); model.put(Entry.ATTRIBUTE_ENTRY_ID, "0"); XmlUtil.beginElement(strBufferListEntryXml, Entry.TAG_ENTRY, model); String strDateModification = I18nService.getLocalizedString(PROPERTY_ENTRY_TYPE_DATE_MODIFICATION_TITLE, locale); XmlUtil.addElementHtml(strBufferListEntryXml, Entry.TAG_TITLE, strDateModification); XmlUtil.endElement(strBufferListEntryXml, Entry.TAG_ENTRY); } for (IEntry entry : listEntryResultSearch) { entry.getXml(plugin, locale, strBufferListEntryXml); } Map<String, String> model = new HashMap<String, String>(); if ((directory.getIdWorkflow() != DirectoryUtils.CONSTANT_ID_NULL) && bWorkflowServiceEnable) { model.put(TAG_DISPLAY, TAG_YES); } else { model.put(TAG_DISPLAY, TAG_NO); } XmlUtil.addEmptyElement(strBufferListEntryXml, TAG_STATUS, model); StringBuilder strBufferDirectoryXml = new StringBuilder(); strBufferDirectoryXml.append(XmlUtil.getXmlHeader()); if (bIsBigExport) { strBufferDirectoryXml .append(directory.getXml(plugin, locale, new StringBuffer(), strBufferListEntryXml)); strBufferListRecordXml = new StringBuffer(EXPORT_STRINGBUFFER_INITIAL_SIZE); strFileOutPut = xmlTransformerService.transformBySourceWithXslCache(strBufferDirectoryXml.toString(), physicalFile.getValue(), strXslId, null, null); String strFinalOutPut = null; if (!bIsCsvExport) { int pos = strFileOutPut.indexOf(EXPORT_XSL_EMPTY_LIST_RECORD); strFinalOutPut = strFileOutPut.substring(0, pos) + EXPORT_XSL_BEGIN_LIST_RECORD; } else { strFinalOutPut = strFileOutPut; } try { bufferedWriter.write(strFinalOutPut); } catch (IOException e) { AppLogService.error(e); } } else { strBufferListRecordXml = new StringBuffer(); } // ----------------------------------------------------------------------- List<Integer> nTmpListId = new ArrayList<Integer>(); int idWorflow = directory.getIdWorkflow(); IRecordService recordService = SpringContextService.getBean(RecordService.BEAN_SERVICE); if (bIsBigExport) { int nXmlHeaderLength = XmlUtil.getXmlHeader().length() - 1; int max = nSize / EXPORT_RECORD_STEP; int max1 = nSize - EXPORT_RECORD_STEP; for (int i = 0; i < max1; i += EXPORT_RECORD_STEP) { AppLogService.debug("Directory export progress : " + (((float) i / nSize) * 100) + "%"); nTmpListId = new ArrayList<Integer>(); int k = i + EXPORT_RECORD_STEP; for (int j = i; j < k; j++) { nTmpListId.add(listResultRecordId.get(j)); } List<Record> nTmpListRecords = recordService.loadListByListId(nTmpListId, plugin); for (Record record : nTmpListRecords) { State state = workflowService.getState(record.getIdRecord(), Record.WORKFLOW_RESOURCE_TYPE, idWorflow, Integer.valueOf(directory.getIdDirectory())); if (bIsCsvExport) { strBufferListRecordXml.append(record.getXmlForCsvExport(plugin, locale, false, state, listEntryResultSearch, false, false, true, bDisplayDateCreation, bDisplayDateModification, hashFields)); } else { strBufferListRecordXml .append(record.getXml(plugin, locale, false, state, listEntryResultSearch, false, false, true, bDisplayDateCreation, bDisplayDateModification, hashFields)); } } strBufferListRecordXml = this.appendPartialContent(strBufferListRecordXml, bufferedWriter, physicalFile, bIsCsvExport, strXslId, nXmlHeaderLength, xmlTransformerService); } // ----------------------------------------------------------------------- int max2 = EXPORT_RECORD_STEP * max; nTmpListId = new ArrayList<Integer>(); for (int i = max2; i < nSize; i++) { nTmpListId.add(listResultRecordId.get((i))); } List<Record> nTmpListRecords = recordService.loadListByListId(nTmpListId, plugin); for (Record record : nTmpListRecords) { State state = workflowService.getState(record.getIdRecord(), Record.WORKFLOW_RESOURCE_TYPE, idWorflow, Integer.valueOf(directory.getIdDirectory())); if (bIsCsvExport) { strBufferListRecordXml.append( record.getXmlForCsvExport(plugin, locale, false, state, listEntryResultSearch, false, false, true, bDisplayDateCreation, bDisplayDateModification, hashFields)); } else { strBufferListRecordXml.append(record.getXml(plugin, locale, false, state, listEntryResultSearch, false, false, true, bDisplayDateCreation, bDisplayDateModification, hashFields)); } } strBufferListRecordXml = this.appendPartialContent(strBufferListRecordXml, bufferedWriter, physicalFile, bIsCsvExport, strXslId, nXmlHeaderLength, xmlTransformerService); strBufferListRecordXml.insert(0, EXPORT_XSL_BEGIN_PARTIAL_EXPORT); strBufferListRecordXml.insert(0, XmlUtil.getXmlHeader()); strBufferListRecordXml.append(EXPORT_XSL_END_PARTIAL_EXPORT); strFileOutPut = xmlTransformerService.transformBySourceWithXslCache(strBufferListRecordXml.toString(), physicalFile.getValue(), strXslId, null, null); try { if (bIsCsvExport) { bufferedWriter.write(strFileOutPut); } else { bufferedWriter.write(strFileOutPut.substring(nXmlHeaderLength)); bufferedWriter .write(EXPORT_XSL_END_LIST_RECORD + EXPORT_XSL_NEW_LINE + EXPORT_XSL_END_DIRECTORY); } } catch (IOException e) { AppLogService.error(e); } finally { IOUtils.closeQuietly(bufferedWriter); IOUtils.closeQuietly(outputStreamWriter); } } else { List<Record> nTmpListRecords = recordService.loadListByListId(listResultRecordId, plugin); for (Record record : nTmpListRecords) { State state = workflowService.getState(record.getIdRecord(), Record.WORKFLOW_RESOURCE_TYPE, idWorflow, Integer.valueOf(directory.getIdDirectory())); if (bIsCsvExport) { strBufferListRecordXml.append( record.getXmlForCsvExport(plugin, locale, false, state, listEntryResultSearch, false, false, true, bDisplayDateCreation, bDisplayDateModification, hashFields)); } else { strBufferListRecordXml.append(record.getXml(plugin, locale, false, state, listEntryResultSearch, false, false, true, bDisplayDateCreation, bDisplayDateModification, hashFields)); } } strBufferDirectoryXml .append(directory.getXml(plugin, locale, strBufferListRecordXml, strBufferListEntryXml)); strShotExportFinalOutPut = xmlTransformerService.transformBySourceWithXslCache( strBufferDirectoryXml.toString(), physicalFile.getValue(), strXslId, null, null); } // ----------------------------------------------------------------------- DirectoryUtils.addHeaderResponse(request, response, strFileName); response.setCharacterEncoding(strEncoding); if (bIsCsvExport) { response.setContentType(CONSTANT_MIME_TYPE_CSV); } else { String strMimeType = FileSystemUtil.getMIMEType(strFileName); if (strMimeType != null) { response.setContentType(strMimeType); } else { response.setContentType(CONSTANT_MIME_TYPE_OCTETSTREAM); } } if (bIsBigExport) { FileChannel in = null; WritableByteChannel writeChannelOut = null; OutputStream out = null; try { in = new FileInputStream(tmpFile).getChannel(); out = response.getOutputStream(); writeChannelOut = Channels.newChannel(out); response.setContentLength(Long.valueOf(in.size()).intValue()); in.transferTo(0, in.size(), writeChannelOut); response.getOutputStream().close(); } catch (IOException e) { AppLogService.error(e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { AppLogService.error(e.getMessage(), e); } } IOUtils.closeQuietly(out); tmpFile.delete(); } } else { PrintWriter out = null; try { out = response.getWriter(); out.print(strShotExportFinalOutPut); } catch (IOException e) { AppLogService.error(e.getMessage(), e); } finally { if (out != null) { out.flush(); out.close(); } } } result.setNoop(true); return result; }