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:fi.vtt.nubomedia.armodule.Ar3DHandler.java

private String getFile(String path) throws IOException {
    RandomAccessFile in = new RandomAccessFile(new File(path), "r");
    FileChannel ch = in.getChannel();
    long size = ch.size();
    byte[] buf = new byte[(int) size];
    in.read(buf, 0, buf.length);/* w  w  w.  ja v  a 2s.  co  m*/
    in.close();
    return new String(buf);
}

From source file:com.fanniemae.ezpie.LogManager.java

public void addFileDetails(String filename, String logGroup) {
    if (_logLevel == LogLevel.ERROR_ONLY) {
        return;//from  w  w  w  .  j  a  v  a  2  s  . c  om
    }

    if (!FileUtilities.isValidFile(_logFilename)) {
        return;
    }

    File fi = new File(filename);
    long lastModified = fi.lastModified();
    Date dtModified = new Date(lastModified);

    try (RandomAccessFile raf = new RandomAccessFile(_logFilename, "rw")) {
        raf.seek(raf.length() - _footerLength);
        raf.write(String.format(_basicLine, logGroup, "File Name", fi.getName(), elapsedTime()).getBytes());
        // Turning off the full path on log, could be security concern.
        // raf.write(String.format(_basicLine, "", "Full Path", filename, elapsedTime()).getBytes())
        raf.write(String
                .format(_basicLine, groupString(""), "Last Modified Date", dtModified.toString(), elapsedTime())
                .getBytes());
        raf.write(String.format(_basicLine, groupString(""), "Size", String.format("%,d bytes", fi.length()),
                elapsedTime()).getBytes());
        raf.write(_footerByteArray);
        raf.close();
    } catch (IOException e) {
        throw new PieException("Error trying to add message to debug page.", e);
    }
}

From source file:com.egt.core.util.JS.java

public static String getOpenFileWindowJavaScript(String spec) {
    Bitacora.trace(JS.class, "getOpenFileWindowJavaScript", spec);
    VelocityContext context = new VelocityContext();
    context.put("url", StringUtils.trimToNull(spec));
    context.put("msg", "Recurso no disponible"); /* TODO: obtener de una tabla de mensajes */
    if (StringUtils.isNotBlank(spec)) {
        RandomAccessFile input;//from   w w  w .j  a  va  2s .  c  o  m
        try {
            URL url = new URL(spec); // throws MalformedURLException
            File file = new File(Utils.getAttachedFileName(url));
            if (file.exists()) {
                input = new RandomAccessFile(file, "r"); // throws FileNotFoundException
                ImageInfo imageInfo = new ImageInfo();
                imageInfo.setInput(input); // input can be InputStream or RandomAccessFile
                imageInfo.setDetermineImageNumber(false); // default is false
                imageInfo.setCollectComments(false); // default is false
                if (imageInfo.check()) {
                    context.put("imageInfo", imageInfo);
                }
                input.close(); // throws IOException
            }
        } catch (MalformedURLException ex) {
            Bitacora.logFatal(ex);
        } catch (FileNotFoundException ex) {
            Bitacora.logFatal(ex);
        } catch (IOException ex) {
            Bitacora.logFatal(ex);
        }
    }
    return merge("js-open-window", context);
}

From source file:org.alfresco.contentstore.ContentStoreTest.java

private void applyPatch(File f, PatchDocument patchDocument) throws FileNotFoundException, IOException {
    int blockSize = checksumService.getBlockSize();

    try (RandomAccessFile file = new RandomAccessFile(f, "rw"); FileChannel fc = file.getChannel()) {
        long start = System.currentTimeMillis();

        for (Patch patch : patchDocument.getPatches()) {
            int blockIndex = patch.getLastMatchIndex();
            long pos = blockIndex * blockSize;
            MappedByteBuffer mem = fc.map(FileChannel.MapMode.READ_WRITE, pos, patch.getSize());
            ByteBuffer bb = ByteBuffer.wrap(patch.getBuffer());
            mem.put(bb);/*from  ww  w.  ja v a  2 s  .c o m*/
        }

        long end = System.currentTimeMillis();
        long time = end - start;

        System.out.println("patch time = " + time);
    }
}

From source file:MSUmpire.SpectrumParser.mzXMLParser.java

private void ParseIndex() throws FileNotFoundException, IOException {
    TotalScan = 0;/*  w  w  w  .j  av a  2 s  .com*/
    ScanIndex = new TreeMap<>();
    try (RandomAccessFile fileHandler = new RandomAccessFile(filename, "r")) {
        StringBuilder sb = new StringBuilder();

        String CurrentLine = "";
        long currentLastPt = fileHandler.length() - 1;
        boolean indexexist = false;
        int linecount = 0;
        while (!(CurrentLine.trim().startsWith("<index name=") | CurrentLine.trim().startsWith("</msRun>"))) {
            //Read backward
            for (long filePointer = currentLastPt; filePointer != -1; filePointer--) {
                fileHandler.seek(filePointer);
                int readByte = fileHandler.readByte();
                if (readByte == 0xA) {
                    if (filePointer == currentLastPt) {
                        continue;
                    } else {
                        currentLastPt = filePointer;
                        break;
                    }
                } else if (readByte == 0xD) {
                    if (filePointer == currentLastPt - 1) {
                        continue;
                    } else {
                        currentLastPt = filePointer;
                        break;
                    }
                }
                sb.append((char) readByte);
            }
            linecount++;
            CurrentLine = sb.reverse().toString();
            sb = new StringBuilder();

            if (CurrentLine.trim().startsWith("</index>")) {
                indexexist = true;
            }

            if (!indexexist && linecount > 10) {
                fileHandler.close();
                Logger.getRootLogger()
                        .debug("File : " + filename + " doesn't have index. the processing will stop.");
                System.exit(1);
            }

            if (CurrentLine.trim().startsWith("<offset id")) {
                int scanNo = Integer.parseInt(
                        CurrentLine.substring(CurrentLine.indexOf("<offset id=\"") + 12).split("\"")[0]);
                long index = (long) Long.parseLong(
                        CurrentLine.substring(CurrentLine.indexOf(">") + 1, CurrentLine.indexOf("</offset>")));
                if (index < 0) {
                    index = index + 2147483647l + 2147483648l;
                }
                if (ScanIndex.containsKey(scanNo + 1) && ScanIndex.get(scanNo + 1) == index) {
                    Logger.getRootLogger().debug("File : " + filename + " index is not correct, ScanNo:"
                            + scanNo + " and " + scanNo + 1 + " have same index");
                    Logger.getRootLogger().debug(
                            "Please use indexmzXML from  TPP package to fix incorrect index of the mzXML file.");
                    Logger.getRootLogger().debug("command: indexmzXML filename.mzXML");
                    System.exit(1);
                }
                ScanIndex.put(scanNo, index);
            } else if (CurrentLine.trim().startsWith("<indexOffset>")) {
                long IndexEnd = (long) Long.parseLong(CurrentLine.substring(
                        CurrentLine.indexOf("<indexOffset>") + 13, CurrentLine.indexOf("</indexOffset>")));
                if (IndexEnd < 0) {
                    IndexEnd = IndexEnd + 2147483647l + 2147483648l;
                }
                ScanIndex.put(Integer.MAX_VALUE, IndexEnd);
            }
        }
        TotalScan = ScanIndex.size();
        sb = null;
        fileHandler.close();
    }
}

From source file:com.lightbox.android.bitmap.BitmapUtils.java

public static void writeBitmapInFile(File file, Bitmap bitmap, CompressFormat compressFormat,
        StringBuilder outMD5) throws IOException {
    // Ensure that the directory exist
    file.getParentFile().mkdirs();/*ww w  .  j  a  v a  2s .com*/

    OutputStream outputStream = null;
    try {
        if (outMD5 != null) {
            // We want a MD5: writing JPEG into a byte array
            outputStream = new ByteArrayOutputStream();
        } else {
            // Directly write to file
            try {
                outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(file), 65536);
            } catch (OutOfMemoryError e) {
                outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(file));
            }
        }
        boolean success = bitmap.compress(compressFormat, FULL_QUALITY, outputStream);
        if (!success) {
            throw new IOException(String.format("Unable to save bitmap as a %s file: %s",
                    (compressFormat == CompressFormat.JPEG) ? "jpeg" : "png",
                    file.getAbsoluteFile().toString()));
        } else {
            if (outMD5 != null) {
                // Calculate MD5 and write the file to disk
                long time = System.currentTimeMillis();
                byte[] jpeg = ((ByteArrayOutputStream) outputStream).toByteArray();
                if (outMD5 != null) {
                    outMD5.append(getMD5String(jpeg));
                }
                DebugLog.d(TAG, "Time to calculate MD5: " + (System.currentTimeMillis() - time));

                time = System.currentTimeMillis();
                RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rwd");
                randomAccessFile.write(jpeg);
                randomAccessFile.close();
                DebugLog.d(TAG, "Time to write to file: " + (System.currentTimeMillis() - time));
            }
        }
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:com.turn.griffin.data.GriffinUploadTask.java

private void uploadFile(FileInfo fileInfo, BitSet availableBlockBitmap) {

    String filename = fileInfo.getFilename();
    long fileVersion = fileInfo.getVersion();
    long blockCount = fileInfo.getBlockCount();
    long blockSize = fileInfo.getBlockSize();
    byte[] buffer = new byte[(int) blockSize];

    GriffinLibCacheUtil libCacheManager = dataManager.getLibCacheManager().get();
    String dataTopicNameForProducer = GriffinKafkaTopicNameUtil.getDataTopicNameForProducer(filename,
            fileVersion);/*  w ww  . java2s. c o  m*/
    GriffinProducer producer = null;
    try {
        String libCacheUploadFilePath = libCacheManager.getUploadFilePath(fileInfo);
        RandomAccessFile libCacheUploadFile = new RandomAccessFile(libCacheUploadFilePath, "r");
        producer = new GriffinProducer(GriffinModule.BROKERS);

        logger.info(String.format("Starting to push %s",
                fileInfo.toString().replaceAll(System.getProperty("line.separator"), " ")));

        int uploadAttempts = 0;
        while (availableBlockBitmap.nextClearBit(0) != blockCount) {

            /* If a new version has arrived abort uploading older version */
            if (!libCacheManager.isLatestGlobalVersion(fileInfo)) {
                logger.info(
                        String.format("Aborting upload for %s version %s as a newer version is now available.",
                                filename, fileVersion));
                break;
            }

            if (uploadAttempts >= maxUploadAttempts) {
                logger.warn(String.format("Unable to upload %s version %s after %s attempts", filename,
                        fileVersion, uploadAttempts));
                String subject = String.format("WARNING: GriffinUploadTask failed for blob:%s", filename);
                String body = String.format(
                        "Action: GriffinUploadTask failed for blob:%s version:%s%n"
                                + "Reason: Unable to upload after %s attempts%n",
                        filename, fileVersion, uploadAttempts);
                GriffinModule.emailAlert(subject, body);
                break;
            }

            int blockToUpload = availableBlockBitmap.nextClearBit(0);
            libCacheUploadFile.seek(blockToUpload * blockSize);
            int bytesRead = libCacheUploadFile.read(buffer);
            DataMessage msg = DataMessage.newBuilder().setBlockSeqNo(blockToUpload).setByteCount(bytesRead)
                    .setData(ByteString.copyFrom(buffer)).build();
            try {
                producer.send(dataTopicNameForProducer, DigestUtils.md5Hex(buffer), msg);
                availableBlockBitmap.set(blockToUpload);
                uploadAttempts = 0;
            } catch (FailedToSendMessageException ftsme) {
                /* Retry the same block again */
                logger.warn(String.format("Unable to send block %s for file: %s version: %s "
                        + "due to FailedToSendMessageException", blockToUpload, filename, fileVersion));
                uploadAttempts++;
            } catch (Exception e) {
                logger.warn(String.format("Unable to send block %s for file: %s version: %s", blockToUpload,
                        filename, fileVersion), e);
                logger.warn("Exception", e);
                uploadAttempts++;
            }
        }
        logger.info(String.format("Ending file upload for file %s version %s to %s", filename, fileVersion,
                dataTopicNameForProducer));
        libCacheUploadFile.close();
    } catch (IOException | RuntimeException e) {
        logger.error(String.format("Unable to upload file %s to %s", filename, dataTopicNameForProducer), e);
        String subject = String.format("WARNING: GriffinUploadTask failed for blob:%s", filename);
        String body = String.format(
                "Action: GriffinUploadTask failed for blob:%s version:%s%n"
                        + "Reason: Exception in GriffinUploadTask%n %s",
                filename, fileVersion, Throwables.getStackTraceAsString(e));
        GriffinModule.emailAlert(subject, body);
    } finally {
        if (producer != null) {
            producer.shutdown();
        }
    }

}

From source file:cn.edu.xmu.tidems.control.support.TideMSUtil.java

public static boolean isHDF5File(final File file) {

    if ((!file.exists()) || (file.isDirectory()) || (file.length() < 1024)) {
        return false;
    }/*from w  w  w. j av  a 2 s. c om*/
    try {
        final RandomAccessFile raf = new RandomAccessFile(file, "r");
        final long sig = raf.readLong(); // The first 8 byte are format signatures of hdf5 file
        raf.close();
        return sig == -8554512424533091830L; // 0x89 48 44 46 0d 0a 1a 0a
    } catch (final Exception e) {
        return false;
    }
}

From source file:net.ontopia.infoset.content.FileContentStore.java

private void allocateNewBlock() throws ContentStoreException {
    RandomAccessFile out = null;/*from  www.  j  ava  2  s  .c  o m*/
    boolean exception_thrown = false;
    try {
        out = new RandomAccessFile(key_file, "rws");

        for (int i = 0; i < MAX_SPINS; i++) {
            // acquire exclusive lock
            FileLock l = out.getChannel().tryLock();

            if (l == null) {
                // wait a little before trying again
                try {
                    Thread.sleep(SPIN_TIMEOUT);
                } catch (InterruptedException e) {
                }
                continue;

            } else {
                try {
                    // allocate new key
                    int old_key;
                    int new_key;
                    String content = null;

                    if (out.length() == 0) {
                        old_key = 0;
                        new_key = old_key + KEY_BLOCK_SIZE;

                    } else {
                        try {
                            content = out.readUTF();
                            old_key = Integer.parseInt(content);
                            new_key = old_key + KEY_BLOCK_SIZE;
                        } catch (NumberFormatException e) {
                            if (content.length() > 100)
                                content = content.substring(0, 100) + "...";
                            throw new ContentStoreException(
                                    "Content store key file corrupted. Contained: '" + content + "'");
                        }
                    }

                    // truncate key file and write out new key
                    out.seek(0);
                    out.writeUTF(Integer.toString(new_key));

                    end_of_key_block = new_key;
                    last_key = old_key;
                    return;
                } finally {
                    // release file lock
                    try {
                        l.release();
                    } catch (Throwable t) {
                        throw new ContentStoreException("Could not release key file lock.", t);
                    }
                }
            }
        }
        throw new ContentStoreException("Block allocation timed out.");

    } catch (ContentStoreException e) {
        exception_thrown = true;
        throw e;

    } catch (Throwable t) {
        exception_thrown = true;
        throw new ContentStoreException(t);

    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                if (!exception_thrown)
                    throw new ContentStoreException("Problems occurred when closing content store.", e);
            }
        }
    }
}

From source file:net.modsec.ms.connector.ConnRequestHandler.java

/**
 * Reads the modsecurity configuration file on modsecurity machine.
 * @param json//from  w  ww .ja  v  a  2s  .  com
 */
@SuppressWarnings("unchecked")
public static void onReadMSConfig(JSONObject json) {

    log.info("onReadMSConfig called.. : " + json.toJSONString());
    MSConfig serviceCfg = MSConfig.getInstance();

    String fileName = serviceCfg.getConfigMap().get("MSConfigFile");
    InputStream ins;
    BufferedReader br;

    try {

        File file = new File(fileName);
        DataInputStream in;

        @SuppressWarnings("resource")
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
        FileLock lock = channel.lock();

        try {

            ins = new FileInputStream(file);
            in = new DataInputStream(ins);
            br = new BufferedReader(new InputStreamReader(in));

            String line = "";

            while ((line = br.readLine()) != null) {

                //log.info("Line :" + line);
                for (ModSecConfigFields field : ModSecConfigFields.values()) {

                    if (line.startsWith(field.toString())) {

                        if (line.trim().split(" ")[0].equals(field.toString())) {
                            json.put(field.toString(), line.trim().split(" ")[1].replace("\"", ""));
                        }

                    }

                }

            }
            log.info("ModSecurity Configurations configurations Loaded ... ");

        } finally {

            lock.release();

        }
        br.close();
        in.close();
        ins.close();

    } catch (FileNotFoundException e1) {

        json.put("status", "1");
        json.put("message", "configuration file not found");
        e1.printStackTrace();

    } catch (IOException | NullPointerException e) {

        json.put("status", "1");
        json.put("message", "configuration file is corrupt");
        e.printStackTrace();

    }

    log.info("Sending Json :" + json.toJSONString());
    ConnectorService.getConnectorProducer().send(json.toJSONString());
    json.clear();

}