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:au.org.ala.layers.grid.GridCacheBuilder.java

private static void writeGroupGRI(File file, ArrayList<Grid> group) {
    Grid g = group.get(0);/*from w  w w. j  a va 2 s .  c o m*/
    RandomAccessFile[] raf = new RandomAccessFile[group.size()];
    RandomAccessFile output = null;

    try {
        output = new RandomAccessFile(file, "rw");

        for (int i = 0; i < group.size(); i++) {
            raf[i] = new RandomAccessFile(group.get(i).filename + ".gri", "r");
        }

        int length = g.ncols * g.nrows;
        int size = 4;
        byte[] b = new byte[size * group.size() * g.ncols];
        float noDataValue = Float.MAX_VALUE * -1;

        byte[] bi = new byte[g.ncols * 8];
        float[][] rows = new float[group.size()][g.ncols];

        for (int i = 0; i < g.nrows; i++) {
            //read
            for (int j = 0; j < raf.length; j++) {
                nextRowOfFloats(rows[j], group.get(j).datatype, group.get(j).byteorderLSB, g.ncols, raf[j], bi,
                        (float) g.nodatavalue);
            }

            //write
            ByteBuffer bb = ByteBuffer.wrap(b);
            bb.order(ByteOrder.LITTLE_ENDIAN);

            for (int k = 0; k < g.ncols; k++) {
                for (int j = 0; j < raf.length; j++) {
                    //float f = getNextValue(raf[j], group.get(j));
                    float f = rows[j][k];
                    if (Float.isNaN(f)) {
                        bb.putFloat(noDataValue);
                    } else {
                        bb.putFloat(f);
                    }
                }
            }
            output.write(b);
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        for (int i = 0; i < raf.length; i++) {
            if (raf[i] != null) {
                try {
                    raf[i].close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:com.openteach.diamond.repository.client.cache.FileLRUCache.java

/**
 * //from   w w  w.j av  a 2 s .  c  om
 */
private void initCtrl() {
    // init index
    String ctrlFileName = String.format("%s.%s", fileName, CTRL_SUFFIX);
    ObjectInputStream in = null;

    // create index file is need
    this.ctrlFile = new File(ctrlFileName);
    if (!this.ctrlFile.exists()) {
        try {
            this.ctrlFile.createNewFile();
        } catch (IOException e) {
            logger.error(String.format("Create index file:%s failed", ctrlFileName), e);
            throw new RuntimeException(e);
        }
    }

    try {
        in = new ObjectInputStream(new FileInputStream(ctrlFile));
        Ctrl ctrl = (Ctrl) in.readObject();
        this.offset = ctrl.offset;
        for (Index index : ctrl.indexs) {
            indexStore.put(index.key, index);
        }
        this.frees.addAll(ctrl.frees);
        ctrl.indexs.clear();
        ctrl.frees.clear();
        ctrl = null;
    } catch (IOException e) {
        logger.error(String.format("Read ctrl file:%s failed", ctrlFileName), e);
    } catch (ClassNotFoundException e) {
        logger.error(String.format("Read ctrl file:%s failed", ctrlFileName), e);
        throw new RuntimeException(e);
    } finally {
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }

    // init data file
    try {
        this.dataFile = new RandomAccessFile(fileName, "rw");
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.github.jeremgamer.preview.actions.Download.java

private void download() {

    GeneralSave gs = new GeneralSave();
    try {/*from  w ww  .  j  a va2s.c o m*/
        gs.load(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    name = gs.getString("name");
    new Thread(new Runnable() {

        @Override
        public void run() {
            if (url == null) {

            } else {
                File archive = new File(System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/"
                        + name + "/data.zip");
                File outputFolder = new File(
                        System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/" + name);

                new File(System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/" + name).mkdirs();
                URL webFile;
                try {
                    webFile = new URL(url);
                    ReadableByteChannel rbc = Channels.newChannel(webFile.openStream());
                    fos = new FileOutputStream(System.getProperty("user.home")
                            + "/AppData/Roaming/.rocketbuilder/" + name + "/data.zip");
                    HttpURLConnection httpConn = (HttpURLConnection) webFile.openConnection();
                    totalBytes = httpConn.getContentLength();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                while (bytesCopied < totalBytes) {
                                    for (CustomProgressBar bar : barList) {
                                        bytesCopied = fos.getChannel().size();
                                        progressValue = (int) (100 * bytesCopied / totalBytes);
                                        bar.setValue(progressValue);
                                        if (bar.isStringPainted()) {
                                            bar.setString(progressValue + "%     " + bytesCopied / 1000 + "/"
                                                    + totalBytes / 1000 + "Kb     tape " + step + "/2");
                                        }
                                    }
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    }).start();
                    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
                    fos.close();
                    step = 2;
                    for (CustomProgressBar bar : barList) {
                        if (bar.isStringPainted()) {
                            bar.setString("tape " + step + "/2 : Extraction");
                        }
                    }

                    for (int timeout = 100; timeout > 0; timeout--) {
                        RandomAccessFile ran = null;

                        try {
                            ran = new RandomAccessFile(archive, "rw");
                            break;
                        } catch (Exception ex) {
                        } finally {
                            if (ran != null)
                                try {
                                    ran.close();
                                } catch (IOException ex) {
                                }

                            ran = null;
                        }

                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                        }
                    }

                    ZipFile zipFile = new ZipFile(archive, Charset.forName("Cp437"));
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        File entryDestination = new File(outputFolder, entry.getName());
                        entryDestination.getParentFile().mkdirs();
                        if (entry.isDirectory())
                            entryDestination.mkdirs();
                        else {
                            InputStream in = zipFile.getInputStream(entry);
                            OutputStream out = new FileOutputStream(entryDestination);
                            IOUtils.copy(in, out);
                            IOUtils.closeQuietly(in);
                            IOUtils.closeQuietly(out);
                            in.close();
                            out.close();
                        }
                    }

                    for (CustomProgressBar bar : barList) {
                        bar.setString("");
                    }

                    zipFile.close();
                    archive.delete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }).start();
}

From source file:se.bitcraze.crazyflielib.bootloader.Bootloader.java

public static byte[] readFile(File file) throws IOException {
    byte[] fileData = new byte[(int) file.length()];
    Logger logger = LoggerFactory.getLogger("Bootloader");
    logger.debug("readFile: " + file.getName() + ", size: " + file.length());
    RandomAccessFile raf = null;//from  w  ww  . java2s  . c o  m
    try {
        raf = new RandomAccessFile(file.getAbsoluteFile(), "r");
        raf.readFully(fileData);
    } finally {
        if (raf != null) {
            try {
                raf.close();
            } catch (IOException ioe) {
                logger.error(ioe.getMessage());
            }
        }
    }
    return fileData;
}

From source file:interactivespaces.master.resource.deployment.internal.NettyHttpRemoteRepositoryMasterWebServerHandler.java

/**
 * Attempt to handle an HTTP request by scanning through all registered
 * handlers./*from  ww w  .  j  a  v  a 2s  . co  m*/
 *
 * @param context
 *          the context for the request
 * @param req
 *          the request
 * @return {@code true} if the request was handled
 *
 * @throws IOException
 *           something bad happened
 */
private boolean handleWebRequest(ChannelHandlerContext context, HttpRequest req) throws IOException {
    String url = req.getUri();
    int pos = url.indexOf('?');
    if (pos != -1)
        url = url.substring(0, pos);

    int luriPrefixLength = uriPrefix.length();
    String bundleName = url.substring(url.indexOf(uriPrefix) + luriPrefixLength);

    File file = featureRepository.getFeatureFile(bundleName);
    if (file == null) {
        return false;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        // sendError(ctx, NOT_FOUND);

        return false;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);

    Channel channel = context.getChannel();

    // Write the initial line and the header.
    channel.write(response);

    // Write the content.
    ChannelFuture writeFuture;
    if (channel.getPipeline().get(SslHandler.class) != null) {
        // Cannot use zero-copy with HTTPS.
        writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192));
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = channel.write(region);
        writeFuture.addListener(new ChannelFutureProgressListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                region.releaseExternalResources();
            }

            @Override
            public void operationProgressed(ChannelFuture arg0, long arg1, long arg2, long arg3)
                    throws Exception {
                // Do nothing
            }

        });
    }

    // Decide whether to close the connection or not.
    if (!isKeepAlive(req)) {
        // Close the connection when the whole content is written out.
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }

    return true;
}

From source file:com.izforge.izpack.util.SelfModifier.java

public static void test(String[] args) {
    // open a File for random access in the sandbox, which will cause
    // deletion//from www  .  j ava 2 s  . co  m
    // of the file and its parent directories to fail until it is closed (by
    // virtue of this java process halting)
    try {
        File sandbox = new File(System.getProperty(BASE_KEY) + ".d");
        File randFile = new File(sandbox, "RandomAccess.tmp");
        RandomAccessFile rand = new RandomAccessFile(randFile, "rw");
        rand.writeChars("Just a test: The JVM has to close 'cuz I won't!\n");

        System.err.print("Deleting sandbox: ");
        FileUtils.deleteDirectory(sandbox);
        System.err.println(sandbox.exists() ? "FAILED" : "SUCCEEDED");
    } catch (Exception x) {
        System.err.println(x.getMessage());
        x.printStackTrace();
    }
}

From source file:com.alibaba.otter.node.etl.common.pipe.impl.http.AbstractHttpPipe.java

protected void decodeFile(File file, String key, String crc) {
    // ??/*from   ww w .ja  v  a  2 s  . c om*/
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(file, "rw");

        long totallength = file.length();
        int keyLength = ByteUtils.stringToBytes(key).length;
        int crcLength = ByteUtils.stringToBytes(crc).length;
        // ?
        long pos = totallength - keyLength - crcLength;
        // 
        raf.seek(pos);
        // ?key
        byte[] keyBytes = new byte[keyLength];
        raf.read(keyBytes, 0, keyLength);
        String keystr = ByteUtils.bytesToString(keyBytes);
        if (!key.equals(keystr)) {
            throw new ChecksumException("unmatch garble key with[" + key + "],[" + keystr + "]");
        }

        // ??
        raf.seek(pos + keyLength);
        byte[] crcBytes = new byte[crcLength];
        raf.read(crcBytes, 0, crcLength);
        String crcStr = ByteUtils.bytesToString(crcBytes);
        if (!crc.equals(crcStr)) {
            throw new ChecksumException("unmatch crc with[" + crc + "],[" + crcStr + "]");
        }

        // 
        raf.setLength(pos);
    } catch (Exception e) {
        throw new PipeException("read_encrypted_error", e);
    } finally {
        IOUtils.closeQuietly(raf);
    }
}

From source file:com.tcl.lzhang1.mymusic.MusicUtil.java

/**
 * get the music info/*from ww  w. j a v a2  s . co m*/
 * 
 * @param musicFile
 * @return
 */
public static SongModel getMusicInfo(File musicFile) {
    SongModel model = new SongModel();
    // retrun null if music file is null or is or directory
    if (musicFile == null || !musicFile.isFile()) {
        return null;
    }

    byte[] buf = new byte[128];
    try {
        Log.d(LOG_TAG, "process music file{" + musicFile.getAbsolutePath() + "}");
        // tag_v1
        RandomAccessFile music = new RandomAccessFile(musicFile, "r");

        music.seek(music.length() - 128);
        music.read(buf);// read tag to buffer
        // tag_v2
        byte[] header = new byte[10];
        music.seek(0);
        music.read(header, 0, 10);
        // if ("ID3".equalsIgnoreCase(new String(header, 0, 3))) {
        // int ID3V2_frame_size = (int) (header[6] & 0x7F) * 0x200000
        // | (int) (header[7] & 0x7F) * 0x400
        // | (int) (header[8] & 0x7F) * 0x80
        // | (int) (header[9] & 0x7F);
        // byte[] FrameHeader = new byte[4];
        // music.seek(ID3V2_frame_size + 10);
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, ID3V2_frame_size, musicFile);
        // } else {
        // byte[] FrameHeader = new byte[4];
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, 0, musicFile);
        // }

        music.close();// close file
        // check length
        // if (buf.length != 128) {
        // throw new
        // ErrorMusicLength(String.format("error music info length, length is:%i",
        // buf.length));
        // }
        //
        // if (!"TAG".equalsIgnoreCase(new String(buf, 0, 3))) {
        // throw new UnknownTagException("unknown tag exception");
        // }
        String songName = null;
        // try {
        // songName = new String(buf, 3, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // e.printStackTrace();
        // songName = new String(buf, 3, 30).trim();
        // }
        String singerName = "";
        // try {
        // singerName = new String(buf, 33, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // singerName = new String(buf, 33, 30).trim();
        // }
        String ablum = "";
        // try {
        // ablum = new String(buf, 63, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // ablum = new String(buf, 63, 30).trim();
        // }
        String year = "";
        // try {
        // year = new String(buf, 93, 4, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // year = new String(buf, 93, 4).trim();
        // // TODO: handle exception
        // }

        String reamrk = "";
        ContentResolver contentResolver = sContext.getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, "_data=?",
                new String[] { musicFile.getAbsolutePath() }, null);
        cursor.moveToFirst();
        if (cursor != null && cursor.getCount() != 0) {
            try {
                if (TextUtils.isEmpty(songName)) {
                    songName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE));
                    singerName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST));
                    ablum = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM));
                    year = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.YEAR));
                }

                long secs = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION));
                model.setTime(secs);
                secs /= 1000;
                model.setHours((int) secs / 3600);
                model.setMinutes(((int) secs % 3600) / 60);
                model.setSeconds(((int) secs % 3600) % 60);
                cursor.close();
            } catch (CursorIndexOutOfBoundsException e) {
                // TODO: handle exception
                if (null != cursor) {
                    cursor.close();
                    cursor = null;
                }
                Log.d(LOG_TAG, "CursorIndexOutOfBoundsException:" + e.getMessage());
                try {
                    songName = new String(buf, 3, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e0) {
                    // TODO: handle exception
                    e.printStackTrace();
                    songName = new String(buf, 3, 30).trim();
                }
                try {
                    singerName = new String(buf, 33, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e1) {
                    // TODO: handle exception
                    singerName = new String(buf, 33, 30).trim();
                }
                try {
                    ablum = new String(buf, 63, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e2) {
                    // TODO: handle exception
                    ablum = new String(buf, 63, 30).trim();
                }
                try {
                    year = new String(buf, 93, 4, "gbk").trim();
                } catch (UnsupportedEncodingException e3) {
                    year = new String(buf, 93, 4).trim();
                    // TODO: handle exception
                }

                try {
                    reamrk = new String(buf, 97, 28, "gbk").trim();
                } catch (UnsupportedEncodingException e4) {
                    // TODO: handle exception
                    reamrk = new String(buf, 97, 28).trim();
                }

            }
        }

        //

        // get the time len

        model.setSongName(songName);
        model.setSingerName(singerName);
        model.setAblumName(ablum);
        model.setFile(musicFile.getAbsolutePath());
        model.setRemark("");
        Log.d(LOG_TAG, String.format("scaned music file[%s],album name[%s],song name[%s],singer name[%s]",
                model.getFile(), model.getAblumName(), model.getSingerName(), model.getSingerName()));

        mSongs.add(model);

        return model;
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return model;
}

From source file:com.github.rholder.esthree.command.GetMultipart.java

public MessageDigest retryingGetWithRange(final long start, final long end)
        throws ExecutionException, RetryException {

    return (MessageDigest) RetryUtils.AWS_RETRYER.call(new Callable<Object>() {
        public MessageDigest call() throws Exception {

            long totalBytes = end - start + 1;
            Progress progress = new TransferProgressWrapper(new TransferProgress());
            progress.setTotalBytesToTransfer(totalBytes);

            if (progressListener != null) {
                progressListener.withTransferProgress(progress).withCompleted((100.0 * start) / contentLength)
                        .withMultiplier(
                                (1.0 * totalBytes / (Math.min(contentLength, chunkSize))) / fileParts.size());
            }//from ww  w . ja  va2 s .  com

            GetObjectRequest req = new GetObjectRequest(bucket, key).withRange(start, end);

            S3Object s3Object = amazonS3Client.getObject(req);
            InputStream input = null;
            try {
                // create the output file, now that we know it actually exists
                if (output == null) {
                    output = new RandomAccessFile(outputFile, "rw");
                }

                // seek to the start of the chunk in the file, just in case we're retrying
                output.seek(start);
                input = s3Object.getObjectContent();

                return copyAndHash(input, totalBytes, progress);
            } finally {
                IOUtils.closeQuietly(input);
            }
        }
    });
}

From source file:com.btoddb.fastpersitentqueue.JournalFileTest.java

@Test
public void testInvalidUUID() throws Exception {
    // can't actuall write an invalid UUID because it's made of two variable length longs
    // only way to get an invalid UUID is to have a truncated file
    JournalFile jf1 = new JournalFile(theFile);
    jf1.initForWriting(new UUID());
    jf1.close();/*  w w w.j a  v  a 2  s .  com*/

    // mess up the UUID
    RandomAccessFile raFile = new RandomAccessFile(theFile, "rw");
    Utils.writeInt(raFile, 1);
    Utils.writeInt(raFile, -1);
    raFile.setLength(raFile.getFilePointer());
    raFile.close();
    //        Utils.writeLong(raFile, numberOfEntries.get());

    JournalFile jf2 = new JournalFile(theFile);
    try {
        jf2.initForReading();
        fail("should have found invalid UUID in the form of truncated file");
    } catch (EOFException e) {
        // good!
    }
}