List of usage examples for java.nio.channels FileChannel size
public abstract long size() throws IOException;
From source file:de.baumann.quitsmoking.fragments.FragmentNotes.java
@Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_backup) { final CharSequence[] options = { getString(R.string.action_backup), getString(R.string.action_restore), getString(R.string.action_delete) }; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setItems(options, new DialogInterface.OnClickListener() { @Override/*from w ww. j a va 2 s.c o m*/ public void onClick(DialogInterface dialog, int item) { if (options[item].equals(getString(R.string.action_backup))) { sharedPref.edit().putString("sortDB", "title").apply(); setNotesList(); File directory = new File( Environment.getExternalStorageDirectory() + "/QuitSmoking/backup/"); if (!directory.exists()) { //noinspection ResultOfMethodCallIgnored directory.mkdirs(); } try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath2 = "//data//" + "de.baumann.quitsmoking" + "//databases//" + "notes.db"; String backupDBPath2 = "//QuitSmoking//" + "//backup//" + "notes.db"; File currentDB2 = new File(data, currentDBPath2); File backupDB2 = new File(sd, backupDBPath2); FileChannel src2 = new FileInputStream(currentDB2).getChannel(); FileChannel dst2 = new FileOutputStream(backupDB2).getChannel(); dst2.transferFrom(src2, 0, src2.size()); src2.close(); dst2.close(); Snackbar snackbar = Snackbar.make(listView, R.string.toast_backup, Snackbar.LENGTH_LONG); snackbar.show(); } } catch (Exception e) { Snackbar snackbar = Snackbar.make(listView, R.string.toast_backup_not, Snackbar.LENGTH_LONG); snackbar.show(); } } if (options[item].equals(getString(R.string.action_restore))) { sharedPref.edit().putString("sortDB", "seqno").apply(); setNotesList(); try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath2 = "//data//" + "de.baumann.quitsmoking" + "//databases//" + "notes.db"; String backupDBPath2 = "//QuitSmoking//" + "//backup//" + "notes.db"; File currentDB2 = new File(data, currentDBPath2); File backupDB2 = new File(sd, backupDBPath2); FileChannel src2 = new FileInputStream(backupDB2).getChannel(); FileChannel dst2 = new FileOutputStream(currentDB2).getChannel(); dst2.transferFrom(src2, 0, src2.size()); src2.close(); dst2.close(); Snackbar snackbar = Snackbar.make(listView, R.string.toast_restore, Snackbar.LENGTH_LONG); snackbar.show(); setNotesList(); } } catch (Exception e) { Snackbar snackbar = Snackbar.make(listView, R.string.toast_restore_not, Snackbar.LENGTH_LONG); snackbar.show(); } } if (options[item].equals(getString(R.string.action_delete))) { sharedPref.edit().putString("sortDB", "icon").apply(); setNotesList(); Snackbar snackbar = Snackbar .make(listView, R.string.note_delete_confirmation, Snackbar.LENGTH_LONG) .setAction(R.string.yes, new View.OnClickListener() { @Override public void onClick(View view) { getActivity().deleteDatabase("notes.db"); setNotesList(); } }); snackbar.show(); } } }); builder.setPositiveButton(R.string.goal_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); builder.show(); } if (id == R.id.action_sort) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); View dialogView = View.inflate(getActivity(), R.layout.dialog_sort, null); final CheckBox ch_title = (CheckBox) dialogView.findViewById(R.id.checkBoxTitle); final CheckBox ch_create = (CheckBox) dialogView.findViewById(R.id.checkBoxCreate); final CheckBox ch_edit = (CheckBox) dialogView.findViewById(R.id.checkBoxEdit); final CheckBox ch_icon = (CheckBox) dialogView.findViewById(R.id.checkBoxIcon); final CheckBox ch_att = (CheckBox) dialogView.findViewById(R.id.checkBoxAtt); if (sharedPref.getString("sortDB", "title").equals("title")) { ch_title.setChecked(true); } else { ch_title.setChecked(false); } if (sharedPref.getString("sortDB", "title").equals("create")) { ch_create.setChecked(true); } else { ch_create.setChecked(false); } if (sharedPref.getString("sortDB", "title").equals("seqno")) { ch_edit.setChecked(true); } else { ch_edit.setChecked(false); } if (sharedPref.getString("sortDB", "title").equals("icon")) { ch_icon.setChecked(true); } else { ch_icon.setChecked(false); } if (sharedPref.getString("sortDB", "title").equals("attachment")) { ch_att.setChecked(true); } else { ch_att.setChecked(false); } ch_title.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { ch_create.setChecked(false); ch_edit.setChecked(false); ch_icon.setChecked(false); ch_att.setChecked(false); sharedPref.edit().putString("sortDB", "title").apply(); setNotesList(); } } }); ch_create.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { ch_edit.setChecked(false); ch_icon.setChecked(false); ch_title.setChecked(false); ch_att.setChecked(false); sharedPref.edit().putString("sortDB", "create").apply(); setNotesList(); } } }); ch_edit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { ch_create.setChecked(false); ch_icon.setChecked(false); ch_title.setChecked(false); ch_att.setChecked(false); sharedPref.edit().putString("sortDB", "seqno").apply(); setNotesList(); } } }); ch_icon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { ch_create.setChecked(false); ch_edit.setChecked(false); ch_title.setChecked(false); ch_att.setChecked(false); sharedPref.edit().putString("sortDB", "icon").apply(); setNotesList(); } } }); ch_att.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { ch_create.setChecked(false); ch_edit.setChecked(false); ch_title.setChecked(false); ch_icon.setChecked(false); sharedPref.edit().putString("sortDB", "attachment").apply(); setNotesList(); } } }); builder.setView(dialogView); builder.setTitle(R.string.action_sort); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); final AlertDialog dialog2 = builder.create(); // Display the custom alert dialog on interface dialog2.show(); return true; } if (id == R.id.action_note) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()); String dateCreate = format.format(date); sharedPref.edit().putString("handleTextCreate", dateCreate).apply(); helper_notes.editNote(getActivity()); } return super.onOptionsItemSelected(item); }
From source file:org.wso2.esb.integration.common.utils.ESBTestCaseUtils.java
/** * Copy the given source file to the given destination * * @param sourceUri source file location * @param destUri destination file location * @throws IOException// ww w . j a v a 2 s . c om */ public static void copyFile(String sourceUri, String destUri) throws IOException { File sourceFile = new File(sourceUri); File destFile = new File(destUri); if (destFile.exists()) { destFile.delete(); } destFile.createNewFile(); FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(sourceFile); fileOutputStream = new FileOutputStream(destFile); FileChannel source = fileInputStream.getChannel(); FileChannel destination = fileOutputStream.getChannel(); destination.transferFrom(source, 0, source.size()); } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(fileOutputStream); } }
From source file:eu.optimis.vc.api.IsoCreator.IsoImageCreation.java
private void storeAgents(File scriptsDirectory) { if (virtualMachine.isHasIPS() || virtualMachine.isHasBTKey() || virtualMachine.isHasVPNKey()) { LOGGER.debug("Adding agents to ISO"); // Add the agent tar ball String agentsTarBallName = "vpn.tar.gz"; // Agents tar ball source File agentsTarBallFileSource = new File( configuration.getAgentsDirectory() + File.separator + agentsTarBallName); LOGGER.debug("agentsTarBallFileSource is: " + agentsTarBallFileSource.getPath()); // Destination folder File agentsIsoDirectory = new File(isoDataDirectory + File.separator + "agents"); agentsIsoDirectory.mkdirs();/*from w w w . j a v a 2s .c o m*/ LOGGER.debug("agentsIsoDirectory is: " + agentsIsoDirectory.getPath()); // Agents tar ball destination File agentsTarBallFileDestination = new File(agentsIsoDirectory + File.separator + agentsTarBallName); LOGGER.debug("agentsTarBallFileDestination is: " + agentsTarBallFileDestination.getPath()); // Copy the file to the iso directory LOGGER.debug("Copying agent file to ISO directory..."); FileChannel source = null; FileChannel destination = null; try { if (!agentsTarBallFileDestination.exists()) { agentsTarBallFileDestination.createNewFile(); } source = new FileInputStream(agentsTarBallFileSource).getChannel(); destination = new FileOutputStream(agentsTarBallFileDestination).getChannel(); destination.transferFrom(source, 0, source.size()); LOGGER.debug( "Copied agent file to ISO directory, size is : " + agentsTarBallFileDestination.length()); agentsTarBallFileDestination.getTotalSpace(); } catch (IOException e) { LOGGER.error( "Failed to create agents tar ball with path: " + agentsTarBallFileDestination.getPath(), e); } finally { if (source != null) { try { source.close(); } catch (IOException e) { LOGGER.error("Failed to close source agents tar ball file with path: " + agentsTarBallFileSource.getPath(), e); } } if (destination != null) { try { destination.close(); } catch (IOException e) { LOGGER.error("Failed to close destination agents tar ball file with path: " + agentsTarBallFileDestination.getPath(), e); } } } // Add the agent script File agentsFile = new File(scriptsDirectory + File.separator + "agents.sh"); try { LOGGER.debug(ATTEMPTING_TO_CREATE_FILE + agentsFile.getPath()); agentsFile.createNewFile(); LOGGER.debug(CREATED_FILE + agentsFile.getPath()); // TODO: This should be stored somewhere else and not hardcoded // Mount location is currently hard coded in the init.d scripts // of the base VM /mnt/context/ String agentsScript = "#!/bin/bash\n" + "#Setup environment\n" + "touch /var/lock/subsys/local\n" + "source /etc/profile\n" + "\n" + "#Extract the agent from the ISO agent directory to /opt/optimis/vpn/\n" + "mkdir -p /opt/optimis\n" + "tar zxvf /mnt/context/agents/" + agentsTarBallName + " -C /opt/optimis/\n" + "chmod -R 777 /opt/optimis/vpn\n" + "\n" + "#Install and start the agents\n" + "\n"; // Add VPN install and init script to // /mnt/context/scripts/agents.sh if (virtualMachine.isHasIPS()) { agentsScript += "#IPS\n" + "/opt/optimis/vpn/IPS_Meta.sh\n" + "/bin/date > /opt/optimis/vpn/dsa.log\n" + "\n"; } // Add VPN install and init script to // /mnt/context/scripts/agents.sh ? // KMS if (virtualMachine.isHasBTKey()) { agentsScript += "#KMS\n" + "/opt/optimis/vpn/KMS_Meta.sh\n" + "/bin/date >> /opt/optimis/vpn/scagent.log\n" + "\n"; } // Add VPN install and init script to // /mnt/context/scripts/agents.sh if (virtualMachine.isHasVPNKey()) { agentsScript += "#VPN\n" + "/opt/optimis/vpn/VPN_Meta.sh\n"; } // Write out the agents file FileOutputStream fos = new FileOutputStream(agentsFile.getPath()); fos.write(agentsScript.getBytes()); fos.close(); LOGGER.debug("Writing agents script complete!"); } catch (IOException e) { LOGGER.error("Failed to create agents script file with path: " + agentsFile.getPath(), e); } } else { LOGGER.debug("Agents not not needed by service!"); } }
From source file:org.pentaho.platform.repository.solution.SolutionRepositoryBase.java
/** * @return int possible values: ISolutionRepository.FILE_ADD_SUCCESSFUL ISolutionRepository.FILE_EXISTS ISolutionRepository.FILE_ADD_FAILED * /*ww w . j ava 2 s . c om*/ * TODO mlowery Why can't this delegate to the other addSolutionFile? */ public int addSolutionFile(final String baseUrl, String path, final String fileName, final File f, boolean overwrite) { if (!path.endsWith("/") && !path.endsWith("\\")) { //$NON-NLS-1$ //$NON-NLS-2$ path += File.separator; } File fNew = new File(baseUrl + path + fileName); int status = ISolutionRepository.FILE_ADD_SUCCESSFUL; if (fNew.exists() && !overwrite) { status = ISolutionRepository.FILE_EXISTS; } else { FileChannel in = null, out = null; try { in = new FileInputStream(f).getChannel(); out = new FileOutputStream(fNew).getChannel(); out.transferFrom(in, 0, in.size()); resetRepository(); } catch (Exception e) { SolutionRepositoryBase.logger.error(e.toString()); status = ISolutionRepository.FILE_ADD_FAILED; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e) { // TODO, we should probably log the error, and return a failure status } } } return status; }
From source file:configuration.Util.java
/** Fast & simple file copy. */ public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try {//from w w w . j av a 2s.com in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { System.out.println("Copy File Directory Failed!"); System.out.println(e); } if (in != null) in.close(); if (out != null) out.close(); }
From source file:adept.io.Reader.java
/** * Reads specified file into a string./*from ww w . j ava 2s . c om*/ * * @param path the path * @return the string */ public String readFileIntoString(String path) { try { String absolutePath = path; // String absolutePath = getAbsolutePathFromClasspathOrFileSystem(path); FileInputStream stream = new FileInputStream(new File(absolutePath)); try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); /* Instead of using default, pass in a decoder. */ return Charset.forName("UTF-8").decode(bb).toString(); } finally { stream.close(); } } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.alu.e3.logger.LogCollector.java
/** * Copy a file from one location to another on the localhost, first moving * (renaming) the source file out of the way of any rotator process, and * then optionally deleting the source file after a successful copy. * Will attempt to replicate the modification time from the original file. * /*ww w . j a v a2 s. c o m*/ * @param sourceFile File to copy * @param destFile Destination file * @param deleteSource If <code>true</code>, will delete original after copy * @return The number of bytes copied * @throws IOException */ public static long copyLocalFile(File sourceFile, File destFile, boolean deleteSource) throws IOException { long bytesCopied = 0L; if ((sourceFile == null) || (destFile == null)) { throw new NullPointerException( "Source or destination file is null (source: " + sourceFile + ", dest: " + destFile + ")"); } if (!destFile.exists()) { destFile.createNewFile(); } String origSourcePath = sourceFile.getPath(); File tempFile = new File(tempNameForSourceFile(sourceFile.getPath())); FileChannel source = null; FileChannel destination = null; IOException cleanupException = null; boolean success = false; // Copy and validate result try { // Rename source file to temporary name before copying if (logger.isDebugEnabled()) { logger.debug("Renaming local file to: {}", tempFile.getPath()); } if (!sourceFile.renameTo(tempFile)) { logger.error("Could not move file to new name: {}", tempFile.getAbsolutePath()); } else { source = new FileInputStream(tempFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); bytesCopied = destination.transferFrom(source, 0, source.size()); copyModificationTime(tempFile, destFile); // Check integrity of copy success = validateFileCopy(tempFile, destFile); if (!success) { logger.warn("Copy of file {} did not pass integrity check!", origSourcePath); } } } catch (IOException ex) { // If there's been an error copying the file, we may be left with a zero-length or incomplete file if (!success) { if (logger.isDebugEnabled()) { logger.debug("Deleting failed copy of local file: {}", destFile.getAbsolutePath()); } destFile.delete(); } } finally { // Use a try-block during cleanup, but only throw exception if the // main file-copy try-block doesn't try { if (source != null) { source.close(); } if (destination != null) { destination.close(); } if (deleteSource && success) { if (logger.isDebugEnabled()) { logger.debug("Deleting local source file: {}", tempFile.getAbsolutePath()); } tempFile.delete(); } else { // Move source file back from temp name if (tempFile == null || !tempFile.renameTo(new File(origSourcePath))) { logger.error("Could not restore original filename: {}", origSourcePath); } } } catch (IOException ex) { logger.warn("IOException during local file-copy cleanup: {}", ex); cleanupException = new IOException(ex); } } if (cleanupException != null) { throw cleanupException; } return bytesCopied; }
From source file:org.apache.hadoop.hdfs.TestFileAppend4.java
/** * Corrupt all of the blocks in the blocksBeingWritten dir * for the specified datanode number. The corruption is * specifically the last checksum chunk of the file being * modified by writing random data into it. *//*ww w . j a v a 2s .com*/ private void corruptDataNode(int dnNumber, CorruptionType type) throws Exception { // get the FS data of the specified datanode File data_dir = new File(System.getProperty("test.build.data"), "dfs/data/data" + Integer.toString(dnNumber * 2 + 1) + "/blocksBeingWritten"); int corrupted = 0; for (File block : data_dir.listFiles()) { // only touch the actual data, not the metadata (with CRC) if (block.getName().startsWith("blk_") && !block.getName().endsWith("meta")) { if (type == CorruptionType.CORRUPT_LAST_CHUNK) { RandomAccessFile file = new RandomAccessFile(block, "rw"); FileChannel channel = file.getChannel(); Random r = new Random(); long lastBlockSize = channel.size() % 512; long position = channel.size() - lastBlockSize; int length = r.nextInt((int) (channel.size() - position + 1)); byte[] buffer = new byte[length]; r.nextBytes(buffer); channel.write(ByteBuffer.wrap(buffer), position); System.out.println("Deliberately corrupting file " + block.getName() + " at offset " + position + " length " + length); file.close(); } else if (type == CorruptionType.TRUNCATE_BLOCK_TO_ZERO) { LOG.info("Truncating block file at " + block); RandomAccessFile blockFile = new RandomAccessFile(block, "rw"); blockFile.setLength(0); blockFile.close(); RandomAccessFile metaFile = new RandomAccessFile(FSDataset.findMetaFile(block), "rw"); metaFile.setLength(0); metaFile.close(); } else if (type == CorruptionType.TRUNCATE_BLOCK_HALF) { FSDatasetTestUtil.truncateBlockFile(block, block.length() / 2); } else { assert false; } ++corrupted; } } assertTrue("Should have some data in bbw to corrupt", corrupted > 0); }
From source file:org.opennms.install.Installer.java
/** * <p>copyFile</p>/*from w ww . j a va 2 s. co m*/ * * @param source a {@link java.lang.String} object. * @param destination a {@link java.lang.String} object. * @param description a {@link java.lang.String} object. * @param recursive a boolean. * @throws java.lang.Exception if any. */ public void copyFile(String source, String destination, String description, boolean recursive) throws Exception { File sourceFile = new File(source); File destinationFile = new File(destination); if (!sourceFile.exists()) { throw new Exception("source file (" + source + ") does not exist!"); } if (!sourceFile.isFile()) { throw new Exception("source file (" + source + ") is not a file!"); } if (!sourceFile.canRead()) { throw new Exception("source file (" + source + ") is not readable!"); } if (destinationFile.exists()) { System.out.print(" - " + destination + " exists, removing... "); if (destinationFile.delete()) { System.out.println("REMOVED"); } else { System.out.println("FAILED"); throw new Exception("unable to delete existing file: " + sourceFile); } } System.out.print(" - copying " + source + " to " + destination + "... "); if (!destinationFile.getParentFile().exists()) { if (!destinationFile.getParentFile().mkdirs()) { throw new Exception("unable to create directory: " + destinationFile.getParent()); } } if (!destinationFile.createNewFile()) { throw new Exception("unable to create file: " + destinationFile); } FileChannel from = null; FileInputStream fisFrom = null; FileChannel to = null; FileOutputStream fisTo = null; try { fisFrom = new FileInputStream(sourceFile); from = fisFrom.getChannel(); fisTo = new FileOutputStream(destinationFile); to = fisTo.getChannel(); to.transferFrom(from, 0, from.size()); } catch (FileNotFoundException e) { throw new Exception("unable to copy " + sourceFile + " to " + destinationFile, e); } finally { IOUtils.closeQuietly(fisTo); IOUtils.closeQuietly(to); IOUtils.closeQuietly(fisFrom); IOUtils.closeQuietly(from); } System.out.println("DONE"); }
From source file:com.clustercontrol.agent.job.PublicKeyThread.java
/** * ?Authorized_key????<BR>/*from ww w . j ava2s . c om*/ * * @param publicKey * @return */ private synchronized boolean addKey(String publicKey) { m_log.debug("add key start"); if (SKIP_KEYFILE_UPDATE) { m_log.info("skipped appending publicKey"); return true; } //??? String fileName = AgentProperties.getProperty(execUser.toLowerCase() + AUTHORIZED_KEY_PATH); m_log.debug("faileName" + fileName); if (fileName == null || fileName.length() == 0) return false; //File? File fi = new File(fileName); RandomAccessFile randomAccessFile = null; FileChannel channel = null; FileLock lock = null; boolean add = false; try { //RandomAccessFile? randomAccessFile = new RandomAccessFile(fi, "rw"); //FileChannel? channel = randomAccessFile.getChannel(); // for (int i = 0; i < (FILELOCK_TIMEOUT / FILELOCK_WAIT); i++) { if (null != (lock = channel.tryLock())) { break; } m_log.info("waiting for locked file... [" + (i + 1) + "/" + (FILELOCK_TIMEOUT / FILELOCK_WAIT) + " : " + fileName + "]"); Thread.sleep(FILELOCK_WAIT); } if (null == lock) { m_log.warn("file locking timeout."); return false; } // (?) synchronized (authKeyLock) { //?? channel.position(channel.size()); //? String writeData = "\n" + publicKey; // m_log.debug("add key : " + writeData); //????? ByteBuffer buffer = ByteBuffer.allocate(512); //??? buffer.clear(); buffer.put(writeData.getBytes()); buffer.flip(); channel.write(buffer); } add = true; } catch (Exception e) { m_log.error(e); } finally { try { if (channel != null) { channel.close(); } if (randomAccessFile != null) { randomAccessFile.close(); } if (lock != null) { // lock.release(); } } catch (Exception e) { } } return add; }