Example usage for java.io RandomAccessFile getFD

List of usage examples for java.io RandomAccessFile getFD

Introduction

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

Prototype

public final FileDescriptor getFD() throws IOException 

Source Link

Document

Returns the opaque file descriptor object associated with this stream.

Usage

From source file:Main.java

public static void main(String[] args) {
    try {//from  w w w .j a v a2  s . co m
        RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

        raf.writeUTF("java2s.com Hello World");

        // set the file pointer at 0 position
        raf.seek(0);

        // read and print the contents of the file
        System.out.println(raf.readUTF());

        // return the file descriptor of the stream
        System.out.println(raf.getFD());

        // close the strea and release resources
        raf.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

From source file:fm.moe.android.util.JSONFileHelper.java

public static void write(final JSONObject object, final String path) throws IOException {
    if (object == null || path == null)
        return;/*  w w  w  .  j  a  va 2s  .co  m*/
    new File(path).delete();
    final RandomAccessFile raf = new RandomAccessFile(path, FILE_MODE_RW);
    final FileWriter fw = new FileWriter(raf.getFD());
    fw.write(object.toString());
    fw.flush();
    fw.close();
}

From source file:org.apache.solr.util.FileUtils.java

/**
 * Copied from Lucene's FSDirectory.fsync(String)
 *
 * @param fullFile the File to be synced to disk
 * @throws IOException if the file could not be synced
 *//*from  w w  w.java2 s .  c  om*/
public static void sync(File fullFile) throws IOException {
    if (fullFile == null || !fullFile.exists())
        throw new FileNotFoundException("File does not exist " + fullFile);

    boolean success = false;
    int retryCount = 0;
    IOException exc = null;
    while (!success && retryCount < 5) {
        retryCount++;
        RandomAccessFile file = null;
        try {
            try {
                file = new RandomAccessFile(fullFile, "rw");
                file.getFD().sync();
                success = true;
            } finally {
                if (file != null)
                    file.close();
            }
        } catch (IOException ioe) {
            if (exc == null)
                exc = ioe;
            try {
                // Pause 5 msec
                Thread.sleep(5);
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
        }
    }
    if (!success)
        // Throw original exception
        throw exc;
}

From source file:Main.java

public static boolean saveApk(File apk, String savePath) {
    FileInputStream in = null;//from w  ww. j a v a  2  s .  c o m
    RandomAccessFile accessFile = null;
    try {
        in = new FileInputStream(apk);
        byte[] buf = new byte[1024 * 4];
        int len;
        File file = new File(savePath);
        accessFile = new RandomAccessFile(file, "rw");
        FileDescriptor fd = accessFile.getFD();
        while ((len = in.read(buf)) != -1) {
            accessFile.write(buf, 0, len);
        }
        fd.sync();
        accessFile.close();
        in.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        try {
            if (in != null) {
                in.close();
            }
            if (accessFile != null) {
                accessFile.close();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }
}

From source file:net.timewalker.ffmq4.storage.data.impl.BlockBasedDataStoreTools.java

private static void initDataFile(File dataFile, int blockCount, int blockSize, boolean forceSync)
        throws DataStoreException {
    log.debug("Creating an empty map file (size=" + blockCount + "x" + blockSize + ") ...");

    // Create an empty file
    try {/*ww  w  .j  av a2 s  .co  m*/
        RandomAccessFile dataFileMap = new RandomAccessFile(dataFile, "rw");
        dataFileMap.setLength((long) blockSize * blockCount);
        if (forceSync)
            dataFileMap.getFD().sync();
        dataFileMap.close();
    } catch (IOException e) {
        throw new DataStoreException("Cannot initialize map file " + dataFile.getAbsolutePath(), e);
    }
}

From source file:de.ailis.wlandsuite.htds.Htds.java

/**
 * Returns the offsets of the tileset MSQ blocks in the specified file.
 * The offsets are determined by reading the raw data of each block and
 * looking at the position in the file./*from  w  w  w .j  av  a  2  s. co  m*/
 *
 * @param file
 *            The file
 * @return The offsets
 * @throws IOException
 *             When file operation fails.
 */

public static List<Integer> getMsqOffsets(final File file) throws IOException {
    List<Integer> offsets;
    RandomAccessFile access;
    FileInputStream stream;
    MsqHeader header;
    long offset;
    byte[] dummy;
    HuffmanInputStream huffmanStream;

    offsets = new ArrayList<Integer>();
    access = new RandomAccessFile(file, "r");
    try {
        stream = new FileInputStream(access.getFD());
        offset = 0;
        while ((header = MsqHeader.read(stream)) != null) {
            offsets.add(Integer.valueOf((int) offset));
            huffmanStream = new HuffmanInputStream(stream);
            dummy = new byte[header.getSize()];
            huffmanStream.read(dummy);
            offset = access.getFilePointer();
        }
    } finally {
        access.close();
    }
    return offsets;
}

From source file:de.ailis.wlandsuite.pics.Pics.java

/**
 * Returns the offsets of the base frame MSQ blocks in the specified file.
 * The offsets are determined by reading the raw data of each block and
 * looking at the current position in the file.
 *
 * @param file/*from   ww w. j av a2s .co m*/
 *            The file
 * @return The offsets
 * @throws IOException
 *             When file operation fails.
 */

public static List<Integer> getMsqOffsets(final File file) throws IOException {
    List<Integer> offsets;
    RandomAccessFile access;
    FileInputStream stream;
    MsqHeader header;
    long offset;
    byte[] dummy;
    boolean baseFrame = true;
    HuffmanInputStream huffmanStream;

    offsets = new ArrayList<Integer>();
    access = new RandomAccessFile(file, "r");
    try {
        stream = new FileInputStream(access.getFD());
        offset = 0;
        while ((header = MsqHeader.read(stream)) != null) {
            if (baseFrame) {
                offsets.add(Integer.valueOf((int) offset));
            }
            baseFrame = !baseFrame;
            huffmanStream = new HuffmanInputStream(stream);
            dummy = new byte[header.getSize()];
            huffmanStream.read(dummy);
            offset = access.getFilePointer();
        }
    } finally {
        access.close();
    }
    return offsets;
}

From source file:org.apache.flume.channel.file.Serialization.java

/**
 * Copy a file using a 64K size buffer. This method will copy the file and
 * then fsync to disk/*from   www.  ja v a 2  s . c  o m*/
 * @param from File to copy - this file should exist
 * @param to Destination file - this file should not exist
 * @return true if the copy was successful
 */
public static boolean copyFile(File from, File to) throws IOException {
    Preconditions.checkNotNull(from, "Source file is null, file copy failed.");
    Preconditions.checkNotNull(to, "Destination file is null, " + "file copy failed.");
    Preconditions.checkState(from.exists(), "Source file: " + from.toString() + " does not exist.");
    Preconditions.checkState(!to.exists(), "Destination file: " + to.toString() + " unexpectedly exists.");

    BufferedInputStream in = null;
    RandomAccessFile out = null; //use a RandomAccessFile for easy fsync
    try {
        in = new BufferedInputStream(new FileInputStream(from));
        out = new RandomAccessFile(to, "rw");
        byte[] buf = new byte[FILE_COPY_BUFFER_SIZE];
        int total = 0;
        while (true) {
            int read = in.read(buf);
            if (read == -1) {
                break;
            }
            out.write(buf, 0, read);
            total += read;
        }
        out.getFD().sync();
        Preconditions.checkState(total == from.length(),
                "The size of the origin file and destination file are not equal.");
        return true;
    } catch (Exception ex) {
        LOG.error("Error while attempting to copy " + from.toString() + " to " + to.toString() + ".", ex);
        Throwables.propagate(ex);
    } finally {
        Throwable th = null;
        try {
            if (in != null) {
                in.close();
            }
        } catch (Throwable ex) {
            LOG.error("Error while closing input file.", ex);
            th = ex;
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException ex) {
            LOG.error("Error while closing output file.", ex);
            Throwables.propagate(ex);
        }
        if (th != null) {
            Throwables.propagate(th);
        }
    }
    // Should never reach here.
    throw new IOException("Copying file: " + from.toString() + " to: " + to.toString() + " may have failed.");
}

From source file:com.gh4a.utils.HttpImageGetter.java

private static Bitmap getBitmap(final File image, int width, int height) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    RandomAccessFile file = null;

    try {//w  w  w . jav a2  s .  c  o  m
        file = new RandomAccessFile(image.getAbsolutePath(), "r");
        FileDescriptor fd = file.getFD();

        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFileDescriptor(fd, null, options);

        int scale = 1;
        while (options.outWidth >= width || options.outHeight >= height) {
            options.outWidth /= 2;
            options.outHeight /= 2;
            scale *= 2;
        }

        options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inSampleSize = scale;

        return BitmapFactory.decodeFileDescriptor(fd, null, options);
    } catch (IOException e) {
        return null;
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                // ignored
            }
        }
    }
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.FSImageLoader.java

/**
 * Load fsimage into the memory.//from  w  ww.  j  av a 2 s. c o  m
 * @param inputFile the filepath of the fsimage to load.
 * @return FSImageLoader
 * @throws IOException if failed to load fsimage.
 */
static FSImageLoader load(String inputFile) throws IOException {
    Configuration conf = new Configuration();
    RandomAccessFile file = new RandomAccessFile(inputFile, "r");
    if (!FSImageUtil.checkFileFormat(file)) {
        throw new IOException("Unrecognized FSImage");
    }

    FsImageProto.FileSummary summary = FSImageUtil.loadSummary(file);

    try (FileInputStream fin = new FileInputStream(file.getFD())) {
        // Map to record INodeReference to the referred id
        ImmutableList<Long> refIdList = null;
        String[] stringTable = null;
        byte[][] inodes = null;
        Map<Long, long[]> dirmap = null;

        ArrayList<FsImageProto.FileSummary.Section> sections = Lists.newArrayList(summary.getSectionsList());
        Collections.sort(sections, new Comparator<FsImageProto.FileSummary.Section>() {
            @Override
            public int compare(FsImageProto.FileSummary.Section s1, FsImageProto.FileSummary.Section s2) {
                FSImageFormatProtobuf.SectionName n1 = FSImageFormatProtobuf.SectionName
                        .fromString(s1.getName());
                FSImageFormatProtobuf.SectionName n2 = FSImageFormatProtobuf.SectionName
                        .fromString(s2.getName());
                if (n1 == null) {
                    return n2 == null ? 0 : -1;
                } else if (n2 == null) {
                    return -1;
                } else {
                    return n1.ordinal() - n2.ordinal();
                }
            }
        });

        for (FsImageProto.FileSummary.Section s : sections) {
            fin.getChannel().position(s.getOffset());
            InputStream is = FSImageUtil.wrapInputStreamForCompression(conf, summary.getCodec(),
                    new BufferedInputStream(new LimitInputStream(fin, s.getLength())));

            if (LOG.isDebugEnabled()) {
                LOG.debug("Loading section " + s.getName() + " length: " + s.getLength());
            }
            switch (FSImageFormatProtobuf.SectionName.fromString(s.getName())) {
            case STRING_TABLE:
                stringTable = loadStringTable(is);
                break;
            case INODE:
                inodes = loadINodeSection(is);
                break;
            case INODE_REFERENCE:
                refIdList = loadINodeReferenceSection(is);
                break;
            case INODE_DIR:
                dirmap = loadINodeDirectorySection(is, refIdList);
                break;
            default:
                break;
            }
        }
        return new FSImageLoader(stringTable, inodes, dirmap);
    }
}