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:com.l2jfree.gameserver.geodata.pathfinding.geonodes.GeoPathFinding.java

private void LoadPathNodeFile(byte rx, byte ry) {
    String fname = "./data/pathnode/" + rx + "_" + ry + ".pn";
    short regionoffset = getRegionOffset(rx, ry);
    _log.info("PathFinding Engine: - Loading: " + fname + " -> region offset: " + regionoffset + "X: " + rx
            + " Y: " + ry);
    File Pn = new File(fname);
    int node = 0, size, index = 0;
    FileChannel roChannel = null;
    try {//from   www . ja va  2s  .c  om
        // Create a read-only memory-mapped file
        roChannel = new RandomAccessFile(Pn, "r").getChannel();
        size = (int) roChannel.size();
        MappedByteBuffer nodes;
        if (Config.FORCE_GEODATA) //Force O/S to Loads this buffer's content into physical memory.
            //it is not guarantee, because the underlying operating system may have paged out some of the buffer's data
            nodes = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, size).load();
        else
            nodes = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);

        // Indexing pathnode files, so we will know where each block starts
        IntBuffer indexs = IntBuffer.allocate(65536);

        while (node < 65536) {
            byte layer = nodes.get(index);
            indexs.put(node++, index);
            index += layer * 10 + 1;
        }
        _pathNodesIndex.set(regionoffset, indexs);
        _pathNodes.set(regionoffset, nodes);
    } catch (Exception e) {
        _log.warn("Failed to Load PathNode File: " + fname + "\n", e);
    } finally {
        try {
            if (roChannel != null)
                roChannel.close();
        } catch (Exception e) {
        }
    }

}

From source file:edu.harvard.i2b2.patientMapping.ui.PatientIDConversionJFrame.java

private void jConvertButtonActionPerformed(java.awt.event.ActionEvent evt) {
    int inputIndex = jInputComboBox.getSelectedIndex() + 1;
    int outputIndex = jOutputComboBox.getSelectedIndex() + 1;

    if ((inputIndex == 2 && outputIndex != 2) || (inputIndex == 4 && outputIndex != 5)) {
        Display.getDefault().syncExec(new Runnable() {
            public void run() {
                MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_WARNING | SWT.OK);

                messageBox.setText("Not valid selections");
                messageBox.setMessage("Input and output pair selected is not valid.");
                messageBox.open();//from   w ww. j  a v  a  2  s .  com

            }
        });
        return;
    }
    //jConvertButton.setCursor(new Cursor(Cursor.WAIT_CURSOR));
    String inputFile = this.jInputFilePathTextField.getText();
    if (inputFile == null || inputFile.equalsIgnoreCase("")) {
        JOptionPane.showMessageDialog(this, "Please select a input file.");
        return;
    }

    final String outputFile = this.jOutputFilePathTextField.getText();
    if (outputFile == null || outputFile.equalsIgnoreCase("")) {
        JOptionPane.showMessageDialog(this, "Please select an output file.");
        return;
    }

    final File oDelete = new File(outputFile);

    Display.getDefault().syncExec(new Runnable() {
        public void run() {
            if (oDelete != null && oDelete.exists()) {
                MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_WARNING | SWT.YES | SWT.NO);

                messageBox.setText("Warning");
                messageBox.setMessage(outputFile + " already exists,\nDo you want to replace it?");
                int buttonID = messageBox.open();
                switch (buttonID) {
                case SWT.YES:
                    oDelete.delete();
                    break;
                case SWT.NO:
                    return;
                case SWT.CANCEL:
                    // does nothing ...
                }
            }
        }
    });
    log.info("Selected output file: " + outputFile);

    //if (fileName != null && fileName.trim().length() > 0) {
    log.info("Selected input file: " + inputFile);

    PatientIDConversionFactory converter = new PatientIDConversionFactory();
    if ((inputIndex == 1 && (outputIndex == 2 || outputIndex == 3))
            || (inputIndex == 3 && (outputIndex == 5 || outputIndex == 6))) {
        converter.sitename(jSiteTextField.getText());
    }
    FileReader fr;
    BufferedReader inbr = null;
    RandomAccessFile f = null;
    //append(f, resultFile.toString());
    jConvertButton.setCursor(new Cursor(Cursor.WAIT_CURSOR));
    try {
        f = new RandomAccessFile(outputFile, "rw");
        fr = new FileReader(new File(inputFile));
        inbr = new BufferedReader(fr);
        //String line = inbr.readLine();
        /*if(!line.startsWith("@@i2b2 patient mapping file@@")) {
           java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
             //setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
             JOptionPane.showMessageDialog(jLabel1, "The file is not in a valid format.", "Error importing", JOptionPane.ERROR_MESSAGE);
          }
           });
           //JOptionPane.showMessageDialog(null, "The file is not a valid.", "Error importing", JOptionPane.ERROR_MESSAGE);
           return;
        }*/
        String line = inbr.readLine();
        //log.info("column name: "+line);         

        int rowCount = 0;

        while (line != null) {
            log.info(line);
            String outputline = "";
            /*String[] cols = line.split(",");
            String id;
            if(cols.length < 2) {
               id = "";
            }
            else {
               id = converter.convert(cols[1], 1, 1);               
            }*/
            outputline = converter.convertLine(line, inputIndex, outputIndex);
            append(f, outputline);//cols[0]+","+id+"\n");
            rowCount++;
            line = inbr.readLine();
        }

        log.info("From " + inputIndex + " to " + outputIndex + " total lines: " + rowCount);
        inbr.close();
        f.close();
    } catch (Exception e) {
        e.printStackTrace();
        if (inbr != null) {
            try {
                inbr.close();
            } catch (Exception e1) {
            }
        }

        if (f != null) {
            try {
                f.close();
            } catch (Exception e1) {
            }
        }
    }

    jConvertButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}

From source file:com.nary.Debug.java

private void intPrintln(String Line) {
    if (!bOn)//from   w ww.ja va 2  s. com
        return;

    String D = com.nary.util.Date.formatNow("dd/MM/yy HH:mm.ss: ") + Line;

    //--[ Write it out to the System Console
    if (bSystemOut)
        System.out.println(D);

    //--[ Write it out to the Servlet Log
    if (servletContext != null)
        servletContext.log(Line);

    D += "\r\n";

    //--[ Write it out to file
    if (bFile) {
        try {

            if (OutFile == null) {
                //-- Log file is closed; lets open it up
                if (filename == null) {
                    return; // we're screwed--give up
                }
                OutFile = new RandomAccessFile(filename, "rw");
                logFileSize = OutFile.length();
                OutFile.seek(logFileSize);
                OutFile.writeBytes("\r\n]--- Logging Started ------[\r\n");
            }

            //-- Write out the line to the logfile
            OutFile.writeBytes(D);
            logFileSize += D.length();

            if (logFileSize > maxLogFileSize)
                rotateLogFile();

        } catch (IOException E) {
            if (OutFile != null) {
                try {
                    OutFile.close();
                } catch (IOException ignore) {
                }
            }
            OutFile = null;
        }
    }
}

From source file:com.phonegap.FileUtils.java

/**
 * Write contents of file.//from w ww .  ja  va2 s . c o m
 * 
 * @param filename         The name of the file.
 * @param data            The contents of the file.
 * @param offset         The position to begin writing the file.         
 * @throws FileNotFoundException, IOException
 */
public long write(String filename, String data, long offset) throws FileNotFoundException, IOException {
    RandomAccessFile file = new RandomAccessFile(filename, "rw");
    file.seek(offset);
    file.writeBytes(data);
    file.close();

    return data.length();
}

From source file:com.vtls.opensource.jhove.JHOVEDocumentFactory.java

/**
 * Populate the representation information for JHOVE Document from a specific File.
 * @param representation a RepInfo // ww  w  . ja  va 2 s  .  c o  m
 * @param file  a File containing the representation information
 * @throws IOException
 */
private void populateRepresentation(RepInfo representation, File file) throws IOException {
    // Iterate through the modules and process.
    Iterator iterator = m_module_list.iterator();
    while (iterator.hasNext()) {
        Module module = (Module) iterator.next();
        module.setBase(m_jhove);
        module.setVerbosity(Module.MINIMUM_VERBOSITY);

        // m_logger.info(module.toString());
        RepInfo persistent = (RepInfo) representation.clone();

        if (module.hasFeature("edu.harvard.hul.ois.jhove.canValidate")) {
            try {
                module.applyDefaultParams();
                if (module.isRandomAccess()) {
                    RandomAccessFile ra_file = new RandomAccessFile(file, "r");
                    module.parse(ra_file, persistent);
                    ra_file.close();
                } else {
                    InputStream stream = new FileInputStream(file);
                    int parse = module.parse(stream, persistent, 0);
                    while (parse != 0) {
                        stream.close();
                        stream = new FileInputStream(file);
                        parse = module.parse(stream, persistent, parse);
                    }
                    stream.close();
                }

                if (persistent.getWellFormed() == RepInfo.TRUE)
                    representation.copy(persistent);
                else
                    representation.setSigMatch(persistent.getSigMatch());
            } catch (Exception e) {
                continue;
            }
        }
    }
}

From source file:com.whizzosoftware.hobson.bootstrap.api.hub.OSGIHubManager.java

@Override
public LogContent getLog(String userId, String hubId, long startIndex, long endIndex) {
    String path = getLogFilePath();

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

        if (startIndex == -1) {
            startIndex = fileLength - endIndex - 1;
            endIndex = fileLength - 1;/* w ww.j a  v a2  s . c  o  m*/
        }
        if (endIndex == -1) {
            endIndex = fileLength - 1;
        }
        if (startIndex > fileLength - 1) {
            throw new HobsonRuntimeException("Requested start index is greater than file length");
        }
        if (endIndex > fileLength - 1) {
            throw new HobsonRuntimeException("Requested end index is greater than file length");
        }

        // jump to start point in file
        file.seek(startIndex);

        // read in appropriate number of bytes
        byte buffer[] = new byte[(int) (endIndex - startIndex)];
        file.read(buffer);

        return new LogContent(startIndex, endIndex, buffer);
    } catch (IOException e) {
        throw new HobsonRuntimeException("Unable to read log file", e);
    }
}

From source file:com.diffplug.gradle.FileMisc.java

/** Concats the first files and writes them to the last file. */
public static void concat(Iterable<File> toMerge, File dst) throws IOException {
    try (FileChannel dstChannel = FileChannel.open(dst.toPath(), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
        for (File file : toMerge) {
            try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
                FileChannel channel = raf.getChannel();
                dstChannel.write(channel.map(FileChannel.MapMode.READ_ONLY, 0, raf.length()));
            }//  w  ww  .  j a  v  a 2 s.  co  m
        }
    }
}

From source file:dk.statsbiblioteket.util.LineReaderTest.java

public void dumpSequentialRA() throws Exception {
    RandomAccessFile ra = new RandomAccessFile(logfile, "r");
    for (int i = 0; i < LINES; i++) {
        ra.readLine();/*ww w.j a  v a2 s .c  o  m*/
    }
    Profiler profiler = new Profiler();
    profiler.setExpectedTotal(SEQUENTIAL_RUNS);
    for (int i = 0; i < SEQUENTIAL_RUNS; i++) {
        ra.seek(0);
        for (int j = 0; j < LINES; j++) {
            ra.readLine();
        }
        profiler.beat();
    }
    System.out.println("Performed " + SEQUENTIAL_RUNS + " full RA reads at "
            + Math.round(profiler.getBps(false)) + " reads/second");
}