List of usage examples for java.io RandomAccessFile getChannel
public final FileChannel getChannel()
From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java
/** * Source:/*from w ww . j a v a 2s .c o m*/ * http://stackoverflow.com/questions/4349075/bitmapfactory-decoderesource * -returns-a-mutable-bitmap-in-android-2-2-and-an-immu * * Converts a immutable bitmap to a mutable bitmap. This operation doesn't * allocates more memory that there is already allocated. * * @param imgIn * - Source image. It will be released, and should not be used * more * @return a copy of imgIn, but immutable. */ public static Bitmap convertBitmapToMutable(Bitmap imgIn) { try { // this is the file going to use temporally to save the bytes. // This file will not be a image, it will store the raw image data. File file = new File(MyApp.context.getFilesDir() + File.separator + "temp.tmp"); // Open an RandomAccessFile // Make sure you have added uses-permission // android:name="android.permission.WRITE_EXTERNAL_STORAGE" // into AndroidManifest.xml file RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); // get the width and height of the source bitmap. int width = imgIn.getWidth(); int height = imgIn.getHeight(); Config type = imgIn.getConfig(); // Copy the byte to the file // Assume source bitmap loaded using options.inPreferredConfig = // Config.ARGB_8888; FileChannel channel = randomAccessFile.getChannel(); MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, imgIn.getRowBytes() * height); imgIn.copyPixelsToBuffer(map); // recycle the source bitmap, this will be no longer used. imgIn.recycle(); System.gc();// try to force the bytes from the imgIn to be released // Create a new bitmap to load the bitmap again. Probably the memory // will be available. imgIn = Bitmap.createBitmap(width, height, type); map.position(0); // load it back from temporary imgIn.copyPixelsFromBuffer(map); // close the temporary file and channel , then delete that also channel.close(); randomAccessFile.close(); // delete the temporary file file.delete(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return imgIn; }
From source file:com.adaptris.fs.NioWorkerTest.java
@Test public void testLockWhileWriting() throws Exception { NioWorker worker = createWorker();/* w w w . ja v a 2 s . c o m*/ File f = File.createTempFile(this.getClass().getSimpleName(), ""); f.delete(); try { RandomAccessFile raf = new RandomAccessFile(f, "rwd"); FileLock lock = raf.getChannel().lock(); try { // Use the write method, because this "bypasses" the file.exists() check worker.write(BYTES, f); fail(); } catch (FsException expected) { assertEquals(OverlappingFileLockException.class, expected.getCause().getClass()); } lock.release(); raf.close(); f.delete(); worker.put(BYTES, f); } finally { FileUtils.deleteQuietly(f); } }
From source file:com.adaptris.fs.NioWorkerTest.java
@Test public void testLockWhileReading() throws Exception { FsWorker worker = createWorker();//from w w w . ja va2 s. co m File f = File.createTempFile(this.getClass().getSimpleName(), ""); f.delete(); try { worker.put(BYTES, f); RandomAccessFile raf = new RandomAccessFile(f, "rwd"); FileLock lock = raf.getChannel().lock(); try { worker.get(f); fail(); } catch (FsException expected) { assertEquals(OverlappingFileLockException.class, expected.getCause().getClass()); } lock.release(); raf.close(); worker.get(f); } finally { FileUtils.deleteQuietly(f); } }
From source file:com.thoughtworks.go.config.GoConfigFileWriter.java
public synchronized void writeToConfigXmlFile(String content) { FileChannel channel = null;/*from w w w . j a v a 2 s .c o m*/ FileOutputStream outputStream = null; FileLock lock = null; try { RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw"); channel = randomAccessFile.getChannel(); lock = channel.lock(); randomAccessFile.seek(0); randomAccessFile.setLength(0); outputStream = new FileOutputStream(randomAccessFile.getFD()); IOUtils.write(content, outputStream, UTF_8); } catch (Exception e) { throw new RuntimeException(e); } finally { if (channel != null && lock != null) { try { lock.release(); channel.close(); IOUtils.closeQuietly(outputStream); } catch (IOException e) { LOGGER.error("Error occured when releasing file lock and closing file.", e); } } } }
From source file:org.squidy.designer.components.pdf.PDFPane.java
public PDFPane(String pdfFileLoc) { super();//from w w w . ja v a 2 s . c om try { // load a pdf from a byte buffer File file = new File(pdfFileLoc); RandomAccessFile raf = new RandomAccessFile(file, "r"); FileChannel channel = raf.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); PDFFile pdffile = new PDFFile(buf); pdfComponents = new PagePanel[pdffile.getNumPages()]; pageHeight = (int) pdffile.getPage(0).getHeight() + 3; pageWidth = (int) pdffile.getPage(0).getWidth() + 1; for (int i = 0; i < pdfComponents.length; i++) { PagePanel p = new PagePanel(); p.setBackground(Color.BLACK); p.setPreferredSize(new Dimension(pageWidth, pageHeight)); PSwing ps = new PSwing(p); ps.setOffset(0, i * pageHeight); addChild(ps); p.showPage(pdffile.getPage(i)); } } catch (IOException e) { if (LOG.isErrorEnabled()) { LOG.error("Error in " + PDFPane.class.getName() + ".", e); } System.out.println(e.getMessage()); } }
From source file:com.asakusafw.runtime.util.lock.LocalFileLockProvider.java
private FileLock getLock(T target, File lockFile, RandomAccessFile fd) throws IOException { try {//from w w w . j ava 2 s . c o m FileLock result = fd.getChannel().tryLock(); if (result == null) { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format("Failed to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$ target, lockFile)); } } return result; } catch (OverlappingFileLockException e) { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format("Failed to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$ target, lockFile)/*, e*/); } return null; } }
From source file:org.apache.hama.bsp.message.io.SyncReadByteBufferInputStream.java
public SyncReadByteBufferInputStream(boolean isSpilled, String fileName) { spilled = isSpilled;//from w w w . j a va 2s.c o m if (isSpilled) { RandomAccessFile f; try { f = new RandomAccessFile(fileName, "r"); fileChannel = f.getChannel(); fileBytesToRead = fileChannel.size(); } catch (FileNotFoundException e) { LOG.error("File not found initializing Synchronous Input Byte Stream", e); throw new RuntimeException(e); } catch (IOException e) { LOG.error("Error initializing Synchronous Input Byte Stream", e); throw new RuntimeException(e); } } }
From source file:com.owncloud.android.oc_framework.network.webdav.FileRequestEntity.java
@Override public void writeRequest(final OutputStream out) throws IOException { //byte[] tmp = new byte[4096]; ByteBuffer tmp = ByteBuffer.allocate(4096); int readResult = 0; // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it // globally in some fashionable manner RandomAccessFile raf = new RandomAccessFile(mFile, "r"); FileChannel channel = raf.getChannel(); Iterator<OnDatatransferProgressListener> it = null; long transferred = 0; long size = mFile.length(); if (size == 0) size = -1;//from w w w .ja va 2 s .co m try { while ((readResult = channel.read(tmp)) >= 0) { out.write(tmp.array(), 0, readResult); tmp.clear(); transferred += readResult; synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readResult, transferred, size, mFile.getName()); } } } } catch (IOException io) { Log.e("FileRequestException", io.getMessage()); throw new RuntimeException( "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); } finally { channel.close(); raf.close(); } }
From source file:net.yacy.document.importer.MediawikiImporter.java
public static byte[] read(final File f, final long start, final int len) { final byte[] b = new byte[len]; RandomAccessFile raf = null; try {//ww w.ja v a 2 s . c om raf = new RandomAccessFile(f, "r"); raf.seek(start); raf.read(b); } catch (final IOException e) { ConcurrentLog.logException(e); return null; } finally { if (raf != null) try { raf.close(); try { raf.getChannel().close(); } catch (final IOException e) { } } catch (final IOException e) { } } return b; }
From source file:eu.alefzero.webdav.FileRequestEntity.java
@Override public void writeRequest(final OutputStream out) throws IOException { //byte[] tmp = new byte[4096]; ByteBuffer tmp = ByteBuffer.allocate(4096); int readResult = 0; // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it // globally in some fashionable manner RandomAccessFile raf = new RandomAccessFile(mFile, "r"); FileChannel channel = raf.getChannel(); Iterator<OnDatatransferProgressListener> it = null; long transferred = 0; long size = mFile.length(); if (size == 0) size = -1;//from w ww . j av a2 s . c om try { while ((readResult = channel.read(tmp)) >= 0) { out.write(tmp.array(), 0, readResult); tmp.clear(); transferred += readResult; synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readResult, transferred, size, mFile.getName()); } } } } catch (IOException io) { Log_OC.e("FileRequestException", io.getMessage()); throw new RuntimeException( "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); } finally { channel.close(); raf.close(); } }