List of usage examples for java.nio.channels FileChannel size
public abstract long size() throws IOException;
From source file:edu.harvard.iq.dataverse.dataaccess.DataFileIO.java
public void copyPath(Path fileSystemPath) throws IOException { long newFileSize = -1; // if this is a local fileystem file, we'll use a // quick Files.copy method: if (isLocalFile()) { Path outputPath = null;/*from w w w . ja v a 2 s .co m*/ try { outputPath = getFileSystemPath(); } catch (IOException ex) { outputPath = null; } if (outputPath != null) { Files.copy(fileSystemPath, outputPath, StandardCopyOption.REPLACE_EXISTING); newFileSize = outputPath.toFile().length(); } } else { // otherwise we'll open a writable byte channel and // copy the source file bytes using Channel.transferTo(): WritableByteChannel writeChannel = null; FileChannel readChannel = null; String failureMsg = null; try { open(DataAccessOption.WRITE_ACCESS); writeChannel = getWriteChannel(); readChannel = new FileInputStream(fileSystemPath.toFile()).getChannel(); long bytesPerIteration = 16 * 1024; // 16K bytes long start = 0; while (start < readChannel.size()) { readChannel.transferTo(start, bytesPerIteration, writeChannel); start += bytesPerIteration; } newFileSize = readChannel.size(); } catch (IOException ioex) { failureMsg = ioex.getMessage(); if (failureMsg == null) { failureMsg = "Unknown exception occured."; } } finally { if (readChannel != null) { try { readChannel.close(); } catch (IOException e) { } } if (writeChannel != null) { try { writeChannel.close(); } catch (IOException e) { } } } if (failureMsg != null) { throw new IOException(failureMsg); } } // if it has worked successfully, we also need to reset the size // of the object. setSize(newFileSize); }
From source file:org.cloudml.connectors.util.MercurialConnector.java
private void copyFile(File f) { FileChannel sourceChannel = null; FileChannel destChannel = null; try {// w ww.j a v a 2 s . c o m sourceChannel = new FileInputStream(f).getChannel(); String destPath; if (!System.getProperty("os.name").toLowerCase().contains("windows")) { destPath = directory + "/" + filename; } else { destPath = directory + "\\" + filename; } File destFile = new File(destPath); if (!destFile.exists()) { destFile.createNewFile(); } destChannel = new FileOutputStream(destFile).getChannel(); destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:edu.cornell.med.icb.goby.modes.ConcatenateCompactReadsMode.java
/** * This version does a quick concat. It does NO filtering. It gathers no stats, * but, will quickly concat multiple compact-reads files together using NIO. * It should be noted that this method is >MUCH< faster. * Copy all of the input files except the last MessageChunksWriter.DELIMITER_LENGTH * bytes of the first n-1 input files and the entire last input file * to the output file./*from w w w . j av a2 s. c o m*/ * @throws IOException */ private void performQuickConcat() throws IOException { System.out.println("quick concatenating files"); File outputFile = new File(outputFilename); if (outputFile.exists()) { System.err.println("The output file already exists. Please delete it before running concat."); return; } outputFile.createNewFile(); FileChannel input = null; FileChannel output = null; long maxChunkSize = 10 * 1024 * 1024; // 10 megabytes at a chunk try { output = new FileOutputStream(outputFile).getChannel(); int lastFileNumToCopy = inputFiles.size() - 1; int curFileNum = 0; for (final File inputFile : inputFiles) { System.out.printf("Reading from %s%n", inputFile); input = new FileInputStream(inputFile).getChannel(); long bytesToCopy = input.size(); if (curFileNum++ < lastFileNumToCopy) { // Compact-reads files end with a delimiter (8 x 0xff) // followed by a 4 byte int 0 (4 x 0x00). Strip // these on all but the last file. bytesToCopy -= (MessageChunksWriter.DELIMITER_LENGTH + 1 + MessageChunksWriter.SIZE_OF_MESSAGE_LENGTH); } // Copy the file about 10 megabytes at a time. It would probably // be marginally faster to just tell NIO to copy the ENTIRE file // in one go, but with very large files Java will freeze until the // entire chunck is copied so this makes for a more responsive program // should you want to ^C in the middle of the copy. Also, with the single // transferTo() you might not see any file size changes in the output file // until the entire copy is complete. long position = 0; while (position < bytesToCopy) { long bytesToCopyThisTime = Math.min(maxChunkSize, bytesToCopy - position); position += input.transferTo(position, bytesToCopyThisTime, output); } input.close(); input = null; } System.out.printf("Concatenated %d files.%n", lastFileNumToCopy + 1); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } } }
From source file:com.wipro.sa349342.wmar.AbstractArchitectCamActivity.java
public void createFCListFromJsonFile() { try {/*w w w. ja v a 2 s .c o m*/ //downloadAndStoreJson("http://jsonblob.com/api/jsonBlob/57b57cc1e4b0dc55a4edf932"); File jsonFile = new File(Environment.getExternalStorageDirectory().getPath(), MainActivityLanding.DefaultJSONFileFromMemeory); /*if (!jsonFile.isFile()) { System.out.println("MyGlobalVariables--readJSONFromMemory::-downloaded json file not found.Switching to default file"); jsonFile = new File(Environment.getExternalStorageDirectory().getPath(), MyGlobalVariables.defaultJSONFileFromMemeory); }*/ FileInputStream stream = new FileInputStream(jsonFile); String jsonStr = null; try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); jsonStr = Charset.defaultCharset().decode(bb).toString(); } finally { stream.close(); } JSONObject jsonObj = new JSONObject(jsonStr); // Getting data JSON Array nodes // JSONArray data = jsonObj.getJSONArray("utility_lines"); addFeaturesInList(jsonObj.getJSONArray("utility_lines"), UtlityLinesFeatureList, "utility_lines"); addFeaturesInList(jsonObj.getJSONArray("equipments"), EquipmentsFeatureList, "equipments"); com.google.android.gms.maps.model.CameraPosition cameraPosition = new com.google.android.gms.maps.model.CameraPosition.Builder() .target(new LatLng(12.8363773, 77.6585139)) //.target(london_eye)//Sets the center of the map to .zoom(19) // Sets the zoom .bearing(0) // Sets the orientation of the camera to east .tilt(0) // Sets the tilt of the camera to 1 degrees .build(); mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } catch (Exception e) { e.printStackTrace(); } }
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 ww .j a v a 2 s . c o m*/ 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.kepler.ssh.LocalExec.java
/** * Copies src file to dst file. If the dst file does not exist, it is * created//from ww w.ja v a2 s .c om */ private void copyFile(File src, File dst) throws IOException { // see if source and destination are the same if (src.equals(dst)) { // do not copy return; } //System.out.println("copying " + src + " to " + dst); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); /* hacking for non-windows */ // set the permission of the target file the same as the source file if (_commandArr[0] == "/bin/sh") { String osName = StringUtilities.getProperty("os.name"); if (osName.startsWith("Mac OS X")) { // chmod --reference does not exist on mac, so do the best // we can using the java file api // WARNING: this relies on the umask to set the group, world // permissions. dst.setExecutable(src.canExecute()); dst.setWritable(src.canWrite()); } else { String cmd = "chmod --reference=" + src.getAbsolutePath() + " " + dst.getAbsolutePath(); try { ByteArrayOutputStream streamOut = new ByteArrayOutputStream(); ByteArrayOutputStream streamErr = new ByteArrayOutputStream(); executeCmd(cmd, streamOut, streamErr); } catch (ExecException e) { log.warn("Tried to set the target file permissions the same as " + "the source but the command failed: " + cmd + "\n" + e); } } } }
From source file:org.talend.designer.core.ui.preferences.I18nPreferencePage.java
private void transferStream(File sourceFile, File targetFile) { if (!sourceFile.exists()) { return;/* w w w . ja va 2 s . c om*/ } try { FileChannel sourceChannel = new FileInputStream(sourceFile.getAbsoluteFile()).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile.getAbsoluteFile()).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.krawler.portal.tools.FileImpl.java
public void copyFile(File source, File destination, boolean lazy) { if (!source.exists()) { return;//from w w w. j a v a 2 s.com } if (lazy) { String oldContent = null; try { oldContent = read(source); } catch (Exception e) { logger.warn(e.getMessage(), e); return; } String newContent = null; try { newContent = read(destination); } catch (Exception e) { logger.warn(e.getMessage(), e); } if ((oldContent == null) || !oldContent.equals(newContent)) { copyFile(source, destination, false); } } else { if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { logger.warn(ioe.getMessage(), ioe); // _log.error(ioe.getMessage()); } } }
From source file:com.cerema.cloud2.operations.UploadFileOperation.java
@Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; boolean localCopyPassed = false, nameCheckPassed = false; File temporalFile = null, originalFile = new File(mOriginalStoragePath), expectedFile = null; try {/*www .j ava 2s .c o m*/ // / rename the file to upload, if necessary if (!mForceOverwrite) { String remotePath = getAvailableRemotePath(client, mRemotePath); mWasRenamed = !remotePath.equals(mRemotePath); if (mWasRenamed) { createNewOCFile(remotePath); } } nameCheckPassed = true; String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile); // / // not // before // getAvailableRemotePath() // !!! expectedFile = new File(expectedPath); // check location of local file; if not the expected, copy to a // temporal file before upload (if COPY is the expected behaviour) if (!mOriginalStoragePath.equals(expectedPath) && mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY) { if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) { result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL); return result; // error condition when the file should be // copied } else { String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath(); mFile.setStoragePath(temporalPath); temporalFile = new File(temporalPath); File temporalParent = temporalFile.getParentFile(); temporalParent.mkdirs(); if (!temporalParent.isDirectory()) { throw new IOException("Unexpected error: parent directory could not be created"); } temporalFile.createNewFile(); if (!temporalFile.isFile()) { throw new IOException("Unexpected error: target file could not be created"); } InputStream in = null; OutputStream out = null; try { // In case document provider schema as 'content://' if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) { Uri uri = Uri.parse(mOriginalStoragePath); in = MainApp.getAppContext().getContentResolver().openInputStream(uri); out = new FileOutputStream(temporalFile); int nRead; byte[] data = new byte[16384]; while (!mCancellationRequested.get() && (nRead = in.read(data, 0, data.length)) != -1) { out.write(data, 0, nRead); } out.flush(); } else { if (!mOriginalStoragePath.equals(temporalPath)) { // preventing // weird // but // possible // situation in = new FileInputStream(originalFile); out = new FileOutputStream(temporalFile); byte[] buf = new byte[1024]; int len; while (!mCancellationRequested.get() && (len = in.read(buf)) > 0) { out.write(buf, 0, len); } } } if (mCancellationRequested.get()) { result = new RemoteOperationResult(new OperationCancelledException()); } } catch (Exception e) { result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED); return result; } finally { try { if (in != null) in.close(); } catch (Exception e) { Log_OC.d(TAG, "Weird exception while closing input stream for " + mOriginalStoragePath + " (ignoring)", e); } try { if (out != null) out.close(); } catch (Exception e) { Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e); } } } } localCopyPassed = (result == null); /// perform the upload if (mChunked && (new File(mFile.getStoragePath())).length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE) { mUploadOperation = new ChunkedUploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict()); } else { mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict()); } Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator(); while (listener.hasNext()) { mUploadOperation.addDatatransferProgressListener(listener.next()); } if (mCancellationRequested.get()) { throw new OperationCancelledException(); } result = mUploadOperation.execute(client); /// move local temporal file or original file to its corresponding // location in the ownCloud local folder if (result.isSuccess()) { if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_FORGET) { mFile.setStoragePath(""); } else { mFile.setStoragePath(expectedPath); File fileToMove = null; if (temporalFile != null) { // FileUploader.LOCAL_BEHAVIOUR_COPY // ; see where temporalFile was // set fileToMove = temporalFile; } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE fileToMove = originalFile; } if (!expectedFile.equals(fileToMove)) { File expectedFolder = expectedFile.getParentFile(); expectedFolder.mkdirs(); if (expectedFolder.isDirectory()) { if (!fileToMove.renameTo(expectedFile)) { // try to copy and then delete expectedFile.createNewFile(); FileChannel inChannel = new FileInputStream(fileToMove).getChannel(); FileChannel outChannel = new FileOutputStream(expectedFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); fileToMove.delete(); } catch (Exception e) { mFile.setStoragePath(null); // forget the local file // by now, treat this as a success; the file was // uploaded; the user won't like that the local file // is not linked, but this should be a very rare // fail; // the best option could be show a warning message // (but not a fail) // result = new // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED); // return result; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } } else { mFile.setStoragePath(null); } } } FileDataStorageManager.triggerMediaScan(originalFile.getAbsolutePath()); FileDataStorageManager.triggerMediaScan(expectedFile.getAbsolutePath()); } else if (result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) { result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT); } } catch (Exception e) { result = new RemoteOperationResult(e); } finally { if (temporalFile != null && !originalFile.equals(temporalFile)) { temporalFile.delete(); } if (result == null) { result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR); } if (result.isSuccess()) { Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage()); } else { if (result.getException() != null) { String complement = ""; if (!nameCheckPassed) { complement = " (while checking file existence in server)"; } else if (!localCopyPassed) { complement = " (while copying local file to " + FileStorageUtils.getSavePath(mAccount.name) + ")"; } Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage() + complement, result.getException()); } else { Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage()); } } } return result; }
From source file:hd3gtv.mydmam.useraction.fileoperation.CopyMove.java
private void copyFile(File source_file, File destination_file) throws IOException { if (destination_file.exists()) { Log2Dump dump = new Log2Dump(); dump.add("source_file", source_file); dump.add("destination_file", destination_file); dump.add("delete_after_copy", delete_after_copy); if (fileexistspolicy == FileExistsPolicy.IGNORE) { Log2.log.debug("Destination file exists, ignore copy/move", dump); return; } else if (fileexistspolicy == FileExistsPolicy.OVERWRITE) { Log2.log.debug("Destination file exists, overwrite it", dump); FileUtils.forceDelete(destination_file); } else if (fileexistspolicy == FileExistsPolicy.RENAME) { // destination_file int cursor = 1; int dot_pos; StringBuilder sb;/* w ww . jav a2s . co m*/ while (destination_file.exists()) { sb = new StringBuilder(); sb.append(destination_file.getParent()); sb.append(File.separator); dot_pos = destination_file.getName().lastIndexOf("."); if (dot_pos > 0) { sb.append(destination_file.getName().substring(0, dot_pos)); sb.append(" ("); sb.append(cursor); sb.append(")"); sb.append( destination_file.getName().substring(dot_pos, destination_file.getName().length())); } else { sb.append(destination_file.getName()); sb.append(" ("); sb.append(cursor); sb.append(")"); } destination_file = new File(sb.toString()); cursor++; } dump.add("new destination file name", destination_file); Log2.log.debug("Destination file exists, change destionation name", dump); } } /** * Imported from org.apache.commons.io.FileUtils * Licensed to the Apache Software Foundation, * http://www.apache.org/licenses/LICENSE-2.0 */ FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(source_file); fos = new FileOutputStream(destination_file); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); if (progression != null) { actual_progress_value = (int) ((pos + progress_copy) / (1024 * 1024)); if (actual_progress_value > last_progress_value) { last_progress_value = actual_progress_value; progression.updateProgress(actual_progress_value, progress_size); } } } } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(input); IOUtils.closeQuietly(fis); } if (source_file.length() != destination_file.length()) { throw new IOException( "Failed to copy full contents from '" + source_file + "' to '" + destination_file + "'"); } if (destination_file.setExecutable(source_file.canExecute()) == false) { Log2.log.error("Can't set Executable status to dest file", new IOException(destination_file.getPath())); } if (destination_file.setLastModified(source_file.lastModified()) == false) { Log2.log.error("Can't set LastModified status to dest file", new IOException(destination_file.getPath())); } }