List of usage examples for java.io RandomAccessFile getChannel
public final FileChannel getChannel()
From source file:ValidateLicenseHeaders.java
/** * Replace a legacy jboss header with the current default header * /*from w ww .j a v a 2 s . c om*/ * @param javaFile - * the java source file * @param endOfHeader - * the offset to the end of the legacy header * @throws IOException - * thrown on failure to replace the header */ static void replaceHeader(File javaFile, long endOfHeader) throws IOException { if (log.isLoggable(Level.FINE)) log.fine("Replacing legacy jboss header in: " + javaFile); RandomAccessFile raf = new RandomAccessFile(javaFile, "rw"); File bakFile = new File(javaFile.getAbsolutePath() + ".bak"); FileOutputStream fos = new FileOutputStream(bakFile); fos.write(DEFAULT_HEADER.getBytes()); FileChannel fc = raf.getChannel(); long count = raf.length() - endOfHeader; fc.transferTo(endOfHeader, count, fos.getChannel()); fc.close(); fos.close(); raf.close(); if (javaFile.delete() == false) log.severe("Failed to delete java file: " + javaFile); if (bakFile.renameTo(javaFile) == false) throw new SyncFailedException("Failed to replace: " + javaFile); }
From source file:storybook.SbApp.java
private static boolean lockInstance(final String lockFile) { try {// w ww . j ava 2s . co m final File file = new File(lockFile); final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); final FileLock fileLock = randomAccessFile.getChannel().tryLock(); if (fileLock != null) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { fileLock.release(); randomAccessFile.close(); file.delete(); } catch (IOException e) { System.err.println("Unable to remove lock file: " + lockFile + "->" + e.getMessage()); } } }); return true; } } catch (IOException e) { System.err.println("Unable to create and/or lock file: " + lockFile + "->" + e.getMessage()); } return false; }
From source file:it.geosolutions.tools.io.file.Copy.java
/** * Copy the input file onto the output file using the specified buffer size. * /* www . j a va2 s . c o m*/ * @param sourceFile * the {@link File} to copy from. * @param destinationFile * the {@link File} to copy to. * @param size * buffer size. * @throws IOException * in case something bad happens. */ public static void copyFile(File sourceFile, File destinationFile, int size) throws IOException { Objects.notNull(sourceFile, destinationFile); if (!sourceFile.exists() || !sourceFile.canRead() || !sourceFile.isFile()) throw new IllegalStateException("Source is not in a legal state."); if (!destinationFile.exists()) { destinationFile.createNewFile(); } if (destinationFile.getAbsolutePath().equalsIgnoreCase(sourceFile.getAbsolutePath())) throw new IllegalArgumentException("Cannot copy a file on itself"); RandomAccessFile s = null, d = null; FileChannel source = null; FileChannel destination = null; try { s = new RandomAccessFile(sourceFile, "r"); source = s.getChannel(); d = new RandomAccessFile(destinationFile, "rw"); destination = d.getChannel(); IOUtils.copyFileChannel(size, source, destination); } finally { if (source != null) { try { source.close(); } catch (Throwable t) { if (LOGGER.isInfoEnabled()) LOGGER.info(t.getLocalizedMessage(), t); } } if (s != null) { try { s.close(); } catch (Throwable t) { if (LOGGER.isInfoEnabled()) LOGGER.info(t.getLocalizedMessage(), t); } } if (destination != null) { try { destination.close(); } catch (Throwable t) { if (LOGGER.isInfoEnabled()) LOGGER.info(t.getLocalizedMessage(), t); } } if (d != null) { try { d.close(); } catch (Throwable t) { if (LOGGER.isInfoEnabled()) LOGGER.info(t.getLocalizedMessage(), t); } } } }
From source file:com.bigdata.dastor.io.SSTableReader.java
private static MappedByteBuffer mmap(String filename, long start, int size) throws IOException { RandomAccessFile raf; try {/*from w w w . j ava2 s . c om*/ raf = new RandomAccessFile(filename, "r"); } catch (FileNotFoundException e) { throw new IOError(e); } try { return raf.getChannel().map(FileChannel.MapMode.READ_ONLY, start, size); } finally { raf.close(); } }
From source file:com.polyvi.xface.util.XFileUtils.java
/** * ?/*from ww w. java 2 s.c o m*/ * * @param filePath * ? * @param size * size? * @return */ public static long truncateFile(String fileName, long size) throws FileNotFoundException, IOException { RandomAccessFile raf = new RandomAccessFile(fileName, "rw"); if (raf.length() >= size) { FileChannel channel = raf.getChannel(); channel.truncate(size); return size; } return raf.length(); }
From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffReader.java
public static boolean isMMMultipageTiff(String directory) throws IOException { File dir = new File(directory); File[] children = dir.listFiles(); File testFile = null;/*from w w w .j ava 2 s. co m*/ for (File child : children) { if (child.isDirectory()) { File[] grandchildren = child.listFiles(); for (File grandchild : grandchildren) { if (grandchild.getName().endsWith(".tif")) { testFile = grandchild; break; } } } else if (child.getName().endsWith(".tif") || child.getName().endsWith(".TIF")) { testFile = child; break; } } if (testFile == null) { throw new IOException("Unexpected file structure: is this an MM dataset?"); } RandomAccessFile ra; try { ra = new RandomAccessFile(testFile, "r"); } catch (FileNotFoundException ex) { ReportingUtils.logError(ex); return false; } FileChannel channel = ra.getChannel(); ByteBuffer tiffHeader = ByteBuffer.allocate(36); ByteOrder bo; channel.read(tiffHeader, 0); char zeroOne = tiffHeader.getChar(0); if (zeroOne == 0x4949) { bo = ByteOrder.LITTLE_ENDIAN; } else if (zeroOne == 0x4d4d) { bo = ByteOrder.BIG_ENDIAN; } else { throw new IOException("Error reading Tiff header"); } tiffHeader.order(bo); int summaryMDHeader = tiffHeader.getInt(32); channel.close(); ra.close(); if (summaryMDHeader == MultipageTiffWriter.SUMMARY_MD_HEADER) { return true; } return false; }
From source file:org.uva.itast.blended.omr.OMRUtils.java
/** * Mtodo que a partir de un fichero pdf de entrada devuelve el * nmero su pginas//www. j a va2s . c om * * @param inputdir * @return pdffile.getNumpages(); * @throws IOException */ public static int getNumpagesPDF(String inputdir) throws IOException { RandomAccessFile raf = new RandomAccessFile(inputdir, "r"); // se carga // la imagen // pdf para // leerla FileChannel channel = raf.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); PDFFile pdffile = new PDFFile(buf); // se crea un objeto de tipo PDFFile // para almacenar las pginas return pdffile.getNumPages(); // se obtiene el nmero de paginas }
From source file:org.apache.jackrabbit.oak.run.SegmentUtils.java
static void compact(File directory, boolean force) throws IOException { FileStore store = openFileStore(directory.getAbsolutePath(), force); try {//from www.ja v a2 s . co m boolean persistCM = Boolean.getBoolean("tar.PersistCompactionMap"); CompactionStrategy compactionStrategy = new CompactionStrategy(false, CompactionStrategy.CLONE_BINARIES_DEFAULT, CompactionStrategy.CleanupType.CLEAN_ALL, 0, CompactionStrategy.MEMORY_THRESHOLD_DEFAULT) { @Override public boolean compacted(Callable<Boolean> setHead) throws Exception { // oak-run is doing compaction single-threaded // hence no guarding needed - go straight ahead // and call setHead return setHead.call(); } }; compactionStrategy.setOfflineCompaction(true); compactionStrategy.setPersistCompactionMap(persistCM); store.setCompactionStrategy(compactionStrategy); store.compact(); } finally { store.close(); } System.out.println(" -> cleaning up"); store = openFileStore(directory.getAbsolutePath(), false); try { for (File file : store.cleanup()) { if (!file.exists() || file.delete()) { System.out.println(" -> removed old file " + file.getName()); } else { System.out.println(" -> failed to remove old file " + file.getName()); } } String head; File journal = new File(directory, "journal.log"); JournalReader journalReader = new JournalReader(journal); try { head = journalReader.iterator().next() + " root " + System.currentTimeMillis() + "\n"; } finally { journalReader.close(); } RandomAccessFile journalFile = new RandomAccessFile(journal, "rw"); try { System.out.println(" -> writing new " + journal.getName() + ": " + head); journalFile.setLength(0); journalFile.writeBytes(head); journalFile.getChannel().force(false); } finally { journalFile.close(); } } finally { store.close(); } }
From source file:net.simon04.guavavfs.VirtualFiles.java
private static MappedByteBuffer map(RandomAccessFile raf, MapMode mode, long size) throws IOException { Closer closer = Closer.create();/*from w w w. ja v a2 s.c om*/ try { FileChannel channel = closer.register(raf.getChannel()); return channel.map(mode, 0, size); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
From source file:org.apache.jackrabbit.oak.run.SegmentTarUtils.java
static void compact(File directory, boolean force) throws IOException { FileStore store = newFileStoreBuilder(directory.getAbsolutePath(), force) .withGCOptions(defaultGCOptions().setOffline()).build(); try {/* w w w. j a v a 2 s. com*/ store.compact(); } finally { store.close(); } System.out.println(" -> cleaning up"); store = newFileStoreBuilder(directory.getAbsolutePath(), force) .withGCOptions(defaultGCOptions().setOffline()).build(); try { for (File file : store.cleanup()) { if (!file.exists() || file.delete()) { System.out.println(" -> removed old file " + file.getName()); } else { System.out.println(" -> failed to remove old file " + file.getName()); } } String head; File journal = new File(directory, "journal.log"); JournalReader journalReader = new JournalReader(journal); try { head = journalReader.next() + " root " + System.currentTimeMillis() + "\n"; } finally { journalReader.close(); } RandomAccessFile journalFile = new RandomAccessFile(journal, "rw"); try { System.out.println(" -> writing new " + journal.getName() + ": " + head); journalFile.setLength(0); journalFile.writeBytes(head); journalFile.getChannel().force(false); } finally { journalFile.close(); } } finally { store.close(); } }