List of usage examples for java.nio.channels FileChannel size
public abstract long size() throws IOException;
From source file:com.rapidminer.tools.Tools.java
public static void copy(File srcPath, File dstPath) throws IOException { if (srcPath.isDirectory()) { if (!dstPath.exists()) { boolean result = dstPath.mkdir(); if (!result) { throw new IOException("Unable to create directoy: " + dstPath); }//www . j a v a 2s . c om } String[] files = srcPath.list(); for (String file : files) { copy(new File(srcPath, file), new File(dstPath, file)); } } else { if (srcPath.exists()) { FileChannel in = null; FileChannel out = null; try (FileInputStream fis = new FileInputStream(srcPath); FileOutputStream fos = new FileOutputStream(dstPath)) { in = fis.getChannel(); out = fos.getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } }
From source file:com.odoo.core.orm.OModel.java
public void exportDB() { FileChannel source; FileChannel destination;//from w w w . j a va 2 s . co m String currentDBPath = getDatabaseLocalPath(); String backupDBPath = OStorageUtils.getDirectoryPath("file") + "/" + getDatabaseName(); File currentDB = new File(currentDBPath); File backupDB = new File(backupDBPath); try { source = new FileInputStream(currentDB).getChannel(); destination = new FileOutputStream(backupDB).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); String subject = "Database Export: " + getDatabaseName(); Uri uri = Uri.fromFile(backupDB); Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_STREAM, uri); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.setType("message/rfc822"); mContext.startActivity(intent); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.clustercontrol.agent.job.PublicKeyThread.java
/** * ?Authorized_key????<BR>/*w ww . j a v a 2 s . com*/ * * @param publicKey * @return true : ?false: */ private synchronized boolean deleteKey(String publicKey) { m_log.debug("delete key start"); if (SKIP_KEYFILE_UPDATE) { m_log.info("skipped deleting publicKey"); return true; } Charset charset = Charset.forName("UTF-8"); CharsetEncoder encoder = charset.newEncoder(); CharsetDecoder decoder = charset.newDecoder(); //??? String fileName = AgentProperties.getProperty(execUser.toLowerCase() + AUTHORIZED_KEY_PATH); if (fileName == null || fileName.length() == 0) return false; //File? File fi = new File(fileName); RandomAccessFile randomAccessFile = null; FileChannel channel = null; FileLock lock = null; boolean delete = 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) { //?? ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); //?? channel.read(buffer); // ???????????0? buffer.flip(); //?? String contents = decoder.decode(buffer).toString(); // ? m_log.debug("contents " + contents.length() + " : " + contents); //?? List<String> keyCheck = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(contents, "\n"); while (tokenizer.hasMoreTokens()) { keyCheck.add(tokenizer.nextToken()); } //?????? int s = keyCheck.lastIndexOf(publicKey); if (s != -1) { // ? m_log.debug("remobe key : " + keyCheck.get(s)); keyCheck.remove(s); } //????? encoder.reset(); buffer.clear(); int i; if (keyCheck.size() > 0) { for (i = 0; i < keyCheck.size() - 1; i++) { encoder.encode(CharBuffer.wrap(keyCheck.get(i) + "\n"), buffer, false); } encoder.encode(CharBuffer.wrap(keyCheck.get(i)), buffer, true); } //??? buffer.flip(); channel.truncate(0); channel.position(0); channel.write(buffer); } delete = true; } catch (IOException e) { m_log.error(e.getMessage(), e); } catch (RuntimeException e) { m_log.error(e.getMessage(), e); } catch (InterruptedException e) { m_log.error(e.getMessage(), e); } finally { try { if (channel != null) { channel.close(); } if (randomAccessFile != null) { randomAccessFile.close(); } //? if (lock != null) { lock.release(); } } catch (Exception e) { } } return delete; }
From source file:com.eucalyptus.blockstorage.DASManager.java
public void dupFile(String oldFileName, String newFileName) { FileOutputStream fileOutputStream = null; FileChannel out = null;//from w w w. j a v a 2 s . com FileInputStream fileInputStream = null; FileChannel in = null; try { fileOutputStream = new FileOutputStream(new File(newFileName)); out = fileOutputStream.getChannel(); fileInputStream = new FileInputStream(new File(oldFileName)); in = fileInputStream.getChannel(); in.transferTo(0, in.size(), out); } catch (Exception ex) { ex.printStackTrace(); } finally { if (fileOutputStream != null) { try { out.close(); fileOutputStream.close(); } catch (IOException e) { LOG.error(e); } } if (fileInputStream != null) { try { in.close(); fileInputStream.close(); } catch (IOException e) { LOG.error(e); } } } }
From source file:com.mellanox.r4h.MiniDFSCluster.java
public static boolean corruptBlock(File blockFile) throws IOException { if (blockFile == null || !blockFile.exists()) { return false; }//w ww . java 2s . c o m // Corrupt replica by writing random bytes into replica Random random = new Random(); RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw"); FileChannel channel = raFile.getChannel(); String badString = "BADBAD"; int rand = random.nextInt((int) channel.size() / 2); raFile.seek(rand); raFile.write(badString.getBytes()); raFile.close(); LOG.warn("Corrupting the block " + blockFile); return true; }
From source file:imageuploader.ImgWindow.java
private void generatedImages(String code, File[] files) throws IOException, IllegalStateException, FTPIllegalReplyException, FTPException, FtpException { int ubicacion; File directory = new File(code); ArrayList<File> imageList = new ArrayList(); DefaultListModel mod = (DefaultListModel) jL_Info.getModel(); if (!directory.exists()) { boolean result = directory.mkdir(); if (!result) { JOptionPane.showMessageDialog(rootPane, "Directory -- Error"); } else {//ww w . jav a 2 s. c om File dir, img; boolean rst; FileChannel source = null; FileChannel dest = null; FtpCredentials.getInstancia().connect(); for (int i = 0; i < files.length; i++) { int val = 1 + i; //Create the Angle directory dir = new File(directory, "Angle" + val); rst = dir.mkdir(); //Copy Images //DefaultListModel mod = (DefaultListModel)jL_Info.getModel(); for (int j = 0; j < mod.getSize(); j++) { img = new File(dir, code + "~" + mod.getElementAt(j).toString() + ".jpg"); rst = img.createNewFile(); imageList.add(img); source = new RandomAccessFile(files[i], "rw").getChannel(); dest = new RandomAccessFile(img, "rw").getChannel(); long position = 0; long count = source.size(); source.transferTo(position, count, dest); if (source != null) { source.close(); } if (dest != null) { dest.close(); } } ubicacion = i + 1; /*Using the private library */ if (jCHBox_MY.isSelected()) { FtpCredentials.getInstancia().getClient().setDir("/Myron/angle" + ubicacion + "Flash"); FtpCredentials.getInstancia().copyImage(imageList); } if (jCHB_CA.isSelected()) { FtpCredentials.getInstancia().getClient().setDir("/canada/angle" + ubicacion + "Flash"); FtpCredentials.getInstancia().copyImage(imageList); } if (jCHB_AZ.isSelected()) { FtpCredentials.getInstancia().getClient().setDir("/australia/angle" + ubicacion + "Flash"); FtpCredentials.getInstancia().copyImage(imageList); } imageList.clear(); } mod.removeAllElements(); jTF_StyleCode.setText(""); //jL_Info.removeAll(); //list.removeAllElements(); JOptionPane.showMessageDialog(rootPane, "Images uploaded"); } } else { JOptionPane.showMessageDialog(rootPane, "There is a folder with the same name in the same location"); } }
From source file:com.bluexml.xforms.controller.alfresco.agents.MappingAgent.java
/** * Copies the content of a source file to a target file. * /*from w w w. j a va 2s. c o m*/ * @param sourceFile * the source file * @param targetFile * the target file * * @throws ServletException * the alfresco controller exception */ private void copyFile(File sourceFile, File targetFile) throws ServletException { FileChannel srcChannel = null; FileChannel dstChannel = null; try { try { srcChannel = new FileInputStream(sourceFile).getChannel(); dstChannel = new FileOutputStream(targetFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { throw new ServletException(e); } finally { if (srcChannel != null) srcChannel.close(); if (dstChannel != null) dstChannel.close(); } } catch (Exception e) { throw new ServletException(e); } }
From source file:it.doqui.index.ecmengine.business.personalization.importer.ArchiveImporterJob.java
private boolean copyFile(File in, File out) { boolean bRet = false; FileChannel inChannel = null; FileChannel outChannel = null; try {//ww w .j a va 2s.c o m inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); // On the Windows plateform, you can't copy a file bigger than 64Mb, an // Exception in thread "main" java.io.IOException: Insufficient system // resources exist to complete the requested service is thrown. // inChannel.transferTo(0, inChannel.size(), outChannel); // magic number for Windows, 64Mb - 32Kb) int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } bRet = true; } catch (IOException e) { //System.out.println( e ); //throw e; } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { } } return bRet; }
From source file:com.ehdev.chronos.lib.Chronos.java
@Override public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) { try {/*from w ww. j a v a2s . co m*/ Log.w(TAG, "Upgrading database, this will drop tables and recreate."); Log.w(TAG, "oldVerion: " + oldVersion + "\tnewVersion: " + newVersion); //Back up database try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/data/com.kopysoft.chronos/databases/" + DATABASE_NAME; String backupDBPath = DATABASE_NAME + ".db"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); } } } catch (Exception e) { Log.e(TAG, "ERROR: Can not move file"); } /* db.execSQL("CREATE TABLE " + TABLE_NAME_CLOCK + " ( _id INTEGER PRIMARY KEY NOT NULL, time LONG NOT NULL, actionReason INTEGER NOT NULL )"); db.execSQL("CREATE TABLE " + TABLE_NAME_NOTE + " ( _id LONG PRIMARY KEY, note_string TEXT NOT NULL, time LONG NOT NULL )"); */ if (oldVersion < 15) { DateTime jobMidnight = DateTime.now().withDayOfWeek(7).minusWeeks(1).toDateMidnight().toDateTime() .withZone(DateTimeZone.getDefault()); Job currentJob = new Job("", 10, jobMidnight, PayPeriodDuration.TWO_WEEKS); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(gContext); currentJob.setPayRate(Float.valueOf(pref.getString("normal_pay", "7.25"))); currentJob.setOvertime(Float.valueOf(pref.getString("over_time_threshold", "40"))); currentJob.setDoubletimeThreshold(Float.valueOf(pref.getString("double_time_threshold", "60"))); SharedPreferences.Editor edit = pref.edit(); edit.remove("8_or_40_hours"); //Moved from string to boolean edit.commit(); String date[] = pref.getString("date", "2011.1.17").split("\\p{Punct}"); jobMidnight = new DateTime(Integer.parseInt(date[0]), Integer.parseInt(date[1]), Integer.parseInt(date[2]), 0, 0); currentJob.setStartOfPayPeriod(jobMidnight.withZone(DateTimeZone.getDefault())); List<Punch> punches = new LinkedList<Punch>(); List<Task> tasks = new LinkedList<Task>(); List<Note> notes = new LinkedList<Note>(); Task newTask; //Basic element newTask = new Task(currentJob, 0, "Regular"); tasks.add(newTask); newTask = new Task(currentJob, 1, "Lunch Break"); newTask.setEnablePayOverride(true); newTask.setPayOverride(-7.25f); tasks.add(newTask); newTask = new Task(currentJob, 2, "Other Break"); newTask.setEnablePayOverride(true); newTask.setPayOverride(-7.25f); tasks.add(newTask); newTask = new Task(currentJob, 3, "Travel"); tasks.add(newTask); newTask = new Task(currentJob, 4, "Admin"); tasks.add(newTask); newTask = new Task(currentJob, 5, "Sick Leave"); tasks.add(newTask); newTask = new Task(currentJob, 6, "Personal Time"); tasks.add(newTask); newTask = new Task(currentJob, 7, "Other"); tasks.add(newTask); newTask = new Task(currentJob, 8, "Holiday Pay"); tasks.add(newTask); Cursor cursor = db.query("clockactions", null, null, null, null, null, "_id desc"); final int colTime = cursor.getColumnIndex("time"); final int colAR = cursor.getColumnIndex("actionReason"); if (cursor.moveToFirst()) { do { long time = cursor.getLong(colTime); Task type = tasks.get(0); if (colAR != -1) { type = tasks.get(cursor.getInt(colAR)); } punches.add(new Punch(currentJob, type, new DateTime(time))); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } cursor = db.query("notes", null, null, null, null, null, "_id desc"); final int colInsertTime = cursor.getColumnIndex("time"); final int colText = cursor.getColumnIndex("note_string"); if (cursor.moveToFirst()) { do { long time = cursor.getLong(colInsertTime); String note = cursor.getString(colText); notes.add(new Note(new DateTime(time), currentJob, note)); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } db.execSQL("DROP TABLE IF EXISTS clockactions"); db.execSQL("DROP TABLE IF EXISTS notes"); db.execSQL("DROP TABLE IF EXISTS misc"); //Recreate DB TableUtils.createTable(connectionSource, Punch.class); //Punch - Create Table TableUtils.createTable(connectionSource, Task.class); //Task - Create Table TableUtils.createTable(connectionSource, Job.class); //Job - Create Table TableUtils.createTable(connectionSource, Note.class); //Task - Create Table //recreate entries Dao<Task, String> taskDAO = getTaskDao(); Dao<Job, String> jobDAO = getJobDao(); Dao<Note, String> noteDAO = getNoteDao(); Dao<Punch, String> punchDOA = getPunchDao(); jobDAO.create(currentJob); for (Task t : tasks) { taskDAO.create(t); } for (Note n : notes) { noteDAO.create(n); } for (Punch p : punches) { punchDOA.create(p); } //"CREATE TABLE " + TABLE_NAME_NOTE " ( _id LONG PRIMARY KEY, note_string TEXT NOT NULL, time LONG NOT NULL )"); } else if (oldVersion == 15) { //Drop //DB - 15 //TableUtils.dropTable(connectionSource, Punch.class, true); //Punch - Drop all //TableUtils.dropTable(connectionSource, Task.class, true); //Task - Drop all //TableUtils.dropTable(connectionSource, Job.class, true); //Job - Drop all //TableUtils.dropTable(connectionSource, Note.class, true); //Note - Drop all Dao<Task, String> taskDAO = getTaskDao(); List<Task> tasks = taskDAO.queryForAll(); db.execSQL("DROP TABLE IF EXISTS tasks"); //create TableUtils.createTable(connectionSource, Task.class); //Task - Create Table for (Task t : tasks) { taskDAO.create(t); } } else if (oldVersion == 16) { //Drop //DB - 15 //TableUtils.dropTable(connectionSource, Punch.class, true); //Punch - Drop all //TableUtils.dropTable(connectionSource, Task.class, true); //Task - Drop all //TableUtils.dropTable(connectionSource, Job.class, true); //Job - Drop all TableUtils.dropTable(connectionSource, Note.class, true); //Note - Drop all //create TableUtils.createTable(connectionSource, Note.class); //Task - Create Table } else if (oldVersion == 17) { //update db from old version Dao<Job, String> dao = getJobDao(); dao.executeRaw("ALTER TABLE `jobs` ADD COLUMN fourtyHourWeek BOOLEAN DEFAULT 1;"); } else if (oldVersion == 18) { Dao<Task, String> taskDAO = getTaskDao(); List<Task> tasks = taskDAO.queryForAll(); Job currentJob = getAllJobs().get(0); if (tasks.size() == 0) { Task newTask; //Basic element newTask = new Task(currentJob, 0, "Regular"); tasks.add(newTask); newTask = new Task(currentJob, 1, "Lunch Break"); newTask.setEnablePayOverride(true); newTask.setPayOverride(-7.25f); tasks.add(newTask); newTask = new Task(currentJob, 2, "Other Break"); newTask.setEnablePayOverride(true); newTask.setPayOverride(-7.25f); tasks.add(newTask); newTask = new Task(currentJob, 3, "Travel"); tasks.add(newTask); newTask = new Task(currentJob, 4, "Admin"); tasks.add(newTask); newTask = new Task(currentJob, 5, "Sick Leave"); tasks.add(newTask); newTask = new Task(currentJob, 6, "Personal Time"); tasks.add(newTask); newTask = new Task(currentJob, 7, "Other"); tasks.add(newTask); newTask = new Task(currentJob, 8, "Holiday Pay"); tasks.add(newTask); for (Task t : tasks) { taskDAO.createOrUpdate(t); } } } else if (oldVersion == 19) { try { TableUtils.dropTable(connectionSource, Job.class, true); //Job - Create Table TableUtils.createTable(connectionSource, Job.class); //Job - Create Table DateTime jobMidnight = new DateMidnight().toDateTime().minusWeeks(1) .withZone(DateTimeZone.getDefault()); Job thisJob = new Job("", 7.25f, jobMidnight, PayPeriodDuration.TWO_WEEKS); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(gContext); try { thisJob.setPayRate(Float.valueOf(pref.getString("normal_pay", "7.25"))); } catch (NumberFormatException e) { thisJob.setPayRate(7.25f); Log.d(TAG, e.getMessage()); } try { thisJob.setOvertime(Float.valueOf(pref.getString("over_time_threshold", "40"))); } catch (NumberFormatException e) { thisJob.setOvertime(40f); Log.d(TAG, e.getMessage()); } try { thisJob.setDoubletimeThreshold( Float.valueOf(pref.getString("double_time_threshold", "60"))); } catch (NumberFormatException e) { thisJob.setDoubletimeThreshold(60f); Log.d(TAG, e.getMessage()); } String date[] = pref.getString("date", "2011.1.17").split("\\p{Punct}"); String time[] = pref.getString("time", "00:00").split("\\p{Punct}"); thisJob.setStartOfPayPeriod(new DateTime(Integer.parseInt(date[0]), Integer.parseInt(date[1]), Integer.parseInt(date[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]))); switch (Integer.parseInt(pref.getString("len_of_month", "2"))) { case 1: thisJob.setDuration(PayPeriodDuration.ONE_WEEK); break; case 2: thisJob.setDuration(PayPeriodDuration.TWO_WEEKS); break; case 3: thisJob.setDuration(PayPeriodDuration.THREE_WEEKS); break; case 4: thisJob.setDuration(PayPeriodDuration.FOUR_WEEKS); break; case 5: thisJob.setDuration(PayPeriodDuration.FULL_MONTH); break; case 6: thisJob.setDuration(PayPeriodDuration.FIRST_FIFTEENTH); break; default: thisJob.setDuration(PayPeriodDuration.TWO_WEEKS); break; } getJobDao().create(thisJob); } catch (SQLException e1) { e1.printStackTrace(); } } else if (oldVersion == 20) { getJobDao().executeRaw( "ALTER TABLE 'jobs' ADD COLUMN '" + Job.OVERTIME_OPTIONS + "' VARCHAR default 'NONE';"); getJobDao().executeRaw("ALTER TABLE 'jobs' ADD COLUMN '" + Job.SATURDAY_OVERRIDE_FIELD + "' VARCHAR default 'NONE';"); getJobDao().executeRaw("ALTER TABLE 'jobs' ADD COLUMN '" + Job.SUNDAY_OVERRIDE_FIELD + "' VARCHAR default 'NONE';"); List<Job> jobList = getAllJobs(); for (Job job : jobList) { GenericRawResults<String[]> rawResults = getJobDao().queryRaw( "select fourtyHourWeek,overTimeEnabled from jobs where job_id = " + job.getID()); String[] results = rawResults.getResults().get(0); if (results[0] == "0") { job.setOvertimeOptions(OvertimeOptions.NONE); } else { if (results[1] == "0") { job.setOvertimeOptions(OvertimeOptions.DAY); } else if (results[1] == "1") { //being paranoid job.setOvertimeOptions(OvertimeOptions.WEEK); } } } //delete stuff getJobDao().executeRaw("ALTER TABLE 'jobs' DROP COLUMN 'fourtyHourWeek';"); getJobDao().executeRaw("ALTER TABLE 'jobs' DROP COLUMN 'overTimeEnabled';"); } } catch (SQLException e) { e.printStackTrace(); Log.e(TAG, "Could not upgrade the table for Thing", e); } }
From source file:org.cytobank.io.LargeFile.java
protected LargeFile(FileChannel fileChannel, long dataAbsoluteOffset, long absoluteLength, int bytesPerRead, String mode) throws IOException { this.fileChannel = fileChannel; this.absoluteDataStart = dataAbsoluteOffset; this.absoluteDataEnd = dataAbsoluteOffset + absoluteLength - 1; this.absoluteLength = absoluteLength; this.bytesPerRead = bytesPerRead; this.relativeSize = toRelative(absoluteLength); if (mode == null || mode.trim().isEmpty()) { this.readable = true; this.writable = false; this.appendable = false; } else {/*from w ww. j a v a2s . c o m*/ mode = mode.toLowerCase(); this.readable = mode.contains(READ_ONLY); this.writable = mode.contains(WRITE_ONLY); this.appendable = mode.contains(WRITE_APPEND_ONLY); } byteBuffer = getBufferFromPool(); if (byteBuffer == null) throw new IOException("Could not get buffer from pool."); this.relativeBufferSize = toRelative(byteBuffer.capacity()); if (relativeBufferSize < 1) throw new IOException("Cannot work with a zero length buffer."); // Guard against attempts to specify a length needed that is larger than the actual file length by checking if the dataAbsoluteOffset + absoluteLength exceeds the length // of the file when in read only. If the file on disk is too short, throwing an IOException. if (!this.appendable) { if (fileChannel.size() < absoluteDataEnd) throw new IOException("File too short. Expected file to be at least " + absoluteDataEnd + " bytes, but it only contains " + fileChannel.size() + " bytes."); } }