Example usage for java.io RandomAccessFile RandomAccessFile

List of usage examples for java.io RandomAccessFile RandomAccessFile

Introduction

In this page you can find the example usage for java.io RandomAccessFile RandomAccessFile.

Prototype

public RandomAccessFile(File file, String mode) throws FileNotFoundException 

Source Link

Document

Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.

Usage

From source file:Main.java

public static Bitmap convertToMutable(Bitmap srcBitmap, String cacheDirPath, String tempFileName) {
    try {/*from   www  .  j  a  va2s . c  om*/
        // 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.
        int index = tempFileName.lastIndexOf(".");
        if (index != -1)
            tempFileName = tempFileName.substring(0, index);
        File file = new File(cacheDirPath + File.separator + tempFileName + ".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 = srcBitmap.getWidth();
        int height = srcBitmap.getHeight();
        Config type = srcBitmap.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, srcBitmap.getRowBytes() * height);
        srcBitmap.copyPixelsToBuffer(map);
        // recycle the source bitmap, this will be no longer used.
        srcBitmap.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.
        srcBitmap = Bitmap.createBitmap(width, height, type);
        map.position(0);
        // load it back from temporary
        srcBitmap.copyPixelsFromBuffer(map);
        // close the temporary file and channel , then delete that also
        channel.close();
        randomAccessFile.close();

        // delete the temp file
        file.delete();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return srcBitmap;
}

From source file:JustOneLock.java

public boolean isAppActive() throws Exception {
    File file = new File(System.getProperty("user.home"), appName + ".tmp");
    channel = new RandomAccessFile(file, "rw").getChannel();

    lock = channel.tryLock();//from   w w  w  .j a  v a2  s  .c o  m
    if (lock == null) {
        lock.release();
        channel.close();
        return true;
    }
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                lock.release();
                channel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    return false;
}

From source file:Main.java

public static double getCpuUsage1() {
    try {//from   w w w  .ja va 2s .  c  o m
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();
        String[] toks = load.split(" ");

        double user1 = Double.parseDouble(toks[2]);
        double system1 = Double.parseDouble(toks[4]);
        double irq1 = Double.parseDouble(toks[7]);
        double idle1 = Double.parseDouble(toks[5]);
        try {
            Thread.sleep(360);
        } catch (Exception e) {
            e.printStackTrace();
        }
        reader.seek(0);
        load = reader.readLine();
        reader.close();
        toks = load.split(" ");
        double user2 = Double.parseDouble(toks[2]);
        double system2 = Double.parseDouble(toks[4]);
        double irq2 = Double.parseDouble(toks[7]);
        double idle2 = Double.parseDouble(toks[5]);

        double user_pass = user2 - user1;
        double system_pass = system2 - system1;
        double irq_pass = irq2 - irq1;
        double idle_pass = idle2 - idle1;
        double usage = (user_pass + system_pass + irq_pass) * 100.00
                / (user_pass + irq_pass + system_pass + idle_pass);
        BigDecimal b = new BigDecimal(usage);
        double res = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return res;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    return 0;

}

From source file:hoot.services.controllers.info.ErrorLog.java

static String getErrorlog(int maxLength) throws IOException {
    File file = new File(ERROR_LOG_PATH);

    try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) {
        long fileLength = file.length();

        long startOffset = 0;
        if (fileLength > maxLength) {
            startOffset = fileLength - maxLength;
        }/*from   w  w w  .  ja  v a2s  .  c om*/

        randomAccessFile.seek(startOffset);

        byte[] buffer = new byte[maxLength];
        randomAccessFile.read(buffer, 0, maxLength);

        return new String(buffer);
    }
}

From source file:Main.java

public static ByteBuffer readBytes(String file) throws IOException {
    ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
    FileChannel fChannel = new RandomAccessFile(file, "r").getChannel();
    fChannel.transferTo(0, fChannel.size(), Channels.newChannel(dataOut));
    fChannel.close();//from   w ww  . j a v a 2 s.c om
    return ByteBuffer.wrap(dataOut.toByteArray());
}

From source file:com.bigfatgun.fixjures.json.JSONSource.java

public static FixtureSource newJsonFile(final File jsonFile) throws FileNotFoundException {
    return new JSONSource(new RandomAccessFile(jsonFile, "r").getChannel());
}

From source file:com.feilong.tools.net.ZClientTest.java

/**
 * Gets the files./*from   w ww.jav a 2s  . com*/
 * 
 * @param ftp
 *            the ftp
 * @param localDir
 *            the local dir
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private static void testGetFiles(FTPClient ftp, File localDir) throws IOException {
    String[] names = ftp.listNames();
    for (String name : names) {
        File file = new File(localDir.getPath() + File.separator + name);
        if (!file.exists()) {
            file.createNewFile();
        }
        long pos = file.length();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.seek(pos);
        ftp.setRestartOffset(pos);
        InputStream is = ftp.retrieveFileStream(name);
        if (is == null) {
            log.info("no such file:" + name);
        } else {
            log.info("start getting file:" + name);
            int b;
            while ((b = is.read()) != -1) {
                raf.write(b);
            }
            is.close();
            if (ftp.completePendingCommand()) {
                log.info("done!");
            } else {
                log.info("can't get file:" + name);
            }
        }
        raf.close();
    }
}

From source file:WordList.java

public static void writeWords(String filename, String[] words) throws IOException {
    // Open the file for read/write access ("rw"). We only need to write,
    // but have to request read access as well
    RandomAccessFile f = new RandomAccessFile(filename, "rw");

    // This array will hold the positions of each word in the file
    long wordPositions[] = new long[words.length];

    // Reserve space at the start of the file for the wordPositions array
    // and the length of that array. 4 bytes for length plus 8 bytes for
    // each long value in the array.
    f.seek(4L + (8 * words.length));/*from w w w  .j  av  a 2  s .c o m*/

    // Now, loop through the words and write them out to the file,
    // recording the start position of each word. Note that the
    // text is written in the UTF-8 encoding, which uses 1, 2, or 3 bytes
    // per character, so we can't assume that the string length equals
    // the string size on the disk. Also note that the writeUTF() method
    // records the length of the string so it can be read by readUTF().
    for (int i = 0; i < words.length; i++) {
        wordPositions[i] = f.getFilePointer(); // record file position
        f.writeUTF(words[i]); // write word
    }

    // Now go back to the beginning of the file and write the positions
    f.seek(0L); // Start at beginning
    f.writeInt(wordPositions.length); // Write array length
    for (int i = 0; i < wordPositions.length; i++)
        // Loop through array
        f.writeLong(wordPositions[i]); // Write array element
    f.close(); // Close the file when done.
}

From source file:com.wabacus.util.FileLockTools.java

public static Object lock(String lockfile) {
    RandomAccessFile raf = null;/*from www  . jav  a  2 s .  c  o m*/
    FileChannel fc = null;
    boolean islocked = true;
    try {
        raf = new RandomAccessFile(new File(lockfile), "rw");
        fc = raf.getChannel();
        FileLock fl = fc.tryLock();
        if (fl != null && fl.isValid()) {
            Map mapResources = new HashMap();
            mapResources.put("RAF", raf);
            mapResources.put("FC", fc);
            mapResources.put("FL", fl);
            return mapResources;
        } else {
            islocked = false;
            return null;
        }
    } catch (Exception e) {
        log.error("?" + lockfile + "?", e);
        return null;
    } finally {
        if (!islocked) {
            release(fc);
            release(raf);

        }
    }

}

From source file:com.baidu.terminator.manager.service.LogServiceImpl.java

@Override
public Log readLog(int linkId, long offset) throws IOException {
    String logFileLocation = LinkLogger.getLogFileLocation(linkId);
    FileUtils.createFile(logFileLocation);

    RandomAccessFile raf = null;//w w w .  java2 s  .com
    List<String> lines = new ArrayList<String>();
    long length = 0;

    try {
        raf = new RandomAccessFile(logFileLocation, "r");
        raf.seek(offset);
        length = raf.length();

        long point = raf.getFilePointer();
        while (point < length) {
            String line = raf.readLine();
            String utf8Line = new String(line.getBytes("8859_1"), "utf-8");
            lines.add(utf8Line);

            if (point - offset >= MAX_READ_BYTES) {
                length = point;
                break;
            }
            point = raf.getFilePointer();
        }
    } finally {
        if (raf != null) {
            raf.close();
        }
    }

    Log log = new Log();
    log.setLogLocation(logFileLocation);
    log.setOffset(length);
    log.setContent(lines);
    return log;
}