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:Diff.java

public static void main(String args[]) {
    RandomAccessFile fh1 = null;/*from   w  w w. j  av a2 s  . c o  m*/
    RandomAccessFile fh2 = null;
    int bufsize; // size of smallest file
    long filesize1 = -1;
    long filesize2 = -1;
    byte buffer1[]; // the two file caches
    byte buffer2[];
    // check what you get as command-line arguments
    if (args.length == 0 || args[0].equals("?")) {
        System.err.println("USAGE: java Diff <file1> <file2> | ?");
        System.exit(0);
    }
    // open file ONE for reading
    try {
        fh1 = new RandomAccessFile(args[0], "r");
        filesize1 = fh1.length();
    } catch (IOException ioErr) {
        System.err.println("Could not find " + args[0]);
        System.err.println(ioErr);
        System.exit(100);
    }
    // open file TWO for reading
    try {
        fh2 = new RandomAccessFile(args[1], "r");
        filesize2 = fh2.length();
    } catch (IOException ioErr) {
        System.err.println("Could not find " + args[1]);
        System.err.println(ioErr);
        System.exit(100);
    }
    if (filesize1 != filesize2) {
        System.out.println("Files differ in size !");
        System.out.println("'" + args[0] + "' is " + filesize1 + " bytes");
        System.out.println("'" + args[1] + "' is " + filesize2 + " bytes");
    }
    // allocate two buffers large enough to hold entire files
    bufsize = (int) Math.min(filesize1, filesize2);
    buffer1 = new byte[bufsize];
    buffer2 = new byte[bufsize];
    try {
        fh1.readFully(buffer1, 0, bufsize);
        fh2.readFully(buffer2, 0, bufsize);

        for (int i = 0; i < bufsize; i++) {
            if (buffer1[i] != buffer2[i]) {
                System.out.println("Files differ at offset " + i);
                break;
            }
        }
    } catch (IOException ioErr) {
        System.err.println("ERROR: An exception occurred while processing the files");
        System.err.println(ioErr);
    } finally {
        try {
            fh1.close();
            fh2.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:RandomFileTest.java

public static void main(String[] args) {
    Employee[] staff = new Employee[3];

    staff[0] = new Employee("Harry Hacker", 35000);
    staff[1] = new Employee("Carl Cracker", 75000);
    staff[2] = new Employee("Tony Tester", 38000);
    try {//w ww .j  ava 2s  .c  om
        DataOutputStream out = new DataOutputStream(new FileOutputStream("employee.dat"));
        for (int i = 0; i < staff.length; i++)
            staff[i].writeData(out);
        out.close();
    } catch (IOException e) {
        System.out.print("Error: " + e);
        System.exit(1);
    }

    try {
        RandomAccessFile in = new RandomAccessFile("employee.dat", "r");
        int count = (int) (in.length() / Employee.RECORD_SIZE);
        Employee[] newStaff = new Employee[count];

        for (int i = count - 1; i >= 0; i--) {
            newStaff[i] = new Employee();
            in.seek(i * Employee.RECORD_SIZE);
            newStaff[i].readData(in);
        }
        for (int i = 0; i < newStaff.length; i++)
            newStaff[i].print();
    } catch (IOException e) {
        System.out.print("Error: " + e);
        System.exit(1);
    }
}

From source file:SampleInterface.java

public static void main(String[] args) {
    try {/*w ww .j  a va2  s  . c o m*/
        RandomAccessFile r = new RandomAccessFile("myfile", "r");
        printInterfaceNames(r);
    } catch (IOException e) {
        System.out.println(e);
    }
}

From source file:RandomFileTest.java

public static void main(String[] args) {
    Employee[] staff = new Employee[3];

    staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
    staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
    staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

    try {//from w  w  w  .  j  ava2  s .  c  o  m
        // save all employee records to the file employee.dat
        DataOutputStream out = new DataOutputStream(new FileOutputStream("employee.dat"));
        for (Employee e : staff)
            e.writeData(out);
        out.close();

        // retrieve all records into a new array
        RandomAccessFile in = new RandomAccessFile("employee.dat", "r");
        // compute the array size
        int n = (int) (in.length() / Employee.RECORD_SIZE);
        Employee[] newStaff = new Employee[n];

        // read employees in reverse order
        for (int i = n - 1; i >= 0; i--) {
            newStaff[i] = new Employee();
            in.seek(i * Employee.RECORD_SIZE);
            newStaff[i].readData(in);
        }
        in.close();

        // print the newly read employee records
        for (Employee e : newStaff)
            System.out.println(e);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Lock.java

public static void main(String args[]) throws IOException, InterruptedException {
    RandomAccessFile file = null; // The file we'll lock
    FileChannel f = null; // The channel to the file
    FileLock lock = null; // The lock object we hold

    try { // The finally clause closes the channel and releases the lock
        // We use a temporary file as the lock file.
        String tmpdir = System.getProperty("java.io.tmpdir");
        String filename = Lock.class.getName() + ".lock";
        File lockfile = new File(tmpdir, filename);

        // Create a FileChannel that can read and write that file.
        // Note that we rely on the java.io package to open the file,
        // in read/write mode, and then just get a channel from it.
        // This will create the file if it doesn't exit. We'll arrange
        // for it to be deleted below, if we succeed in locking it.
        file = new RandomAccessFile(lockfile, "rw");
        f = file.getChannel();//w  w w.  jav  a  2 s  . c  om

        // Try to get an exclusive lock on the file.
        // This method will return a lock or null, but will not block.
        // See also FileChannel.lock() for a blocking variant.
        lock = f.tryLock();

        if (lock != null) {
            // We obtained the lock, so arrange to delete the file when
            // we're done, and then write the approximate time at which
            // we'll relinquish the lock into the file.
            lockfile.deleteOnExit(); // Just a temporary file

            // First, we need a buffer to hold the timestamp
            ByteBuffer bytes = ByteBuffer.allocate(8); // a long is 8 bytes

            // Put the time in the buffer and flip to prepare for writing
            // Note that many Buffer methods can be "chained" like this.
            bytes.putLong(System.currentTimeMillis() + 10000).flip();

            f.write(bytes); // Write the buffer contents to the channel
            f.force(false); // Force them out to the disk
        } else {
            // We didn't get the lock, which means another instance is
            // running. First, let the user know this.
            System.out.println("Another instance is already running");

            // Next, we attempt to read the file to figure out how much
            // longer the other instance will be running. Since we don't
            // have a lock, the read may fail or return inconsistent data.
            try {
                ByteBuffer bytes = ByteBuffer.allocate(8);
                f.read(bytes); // Read 8 bytes from the file
                bytes.flip(); // Flip buffer before extracting bytes
                long exittime = bytes.getLong(); // Read bytes as a long
                // Figure out how long that time is from now and round
                // it to the nearest second.
                long secs = (exittime - System.currentTimeMillis() + 500) / 1000;
                // And tell the user about it.
                System.out.println("Try again in about " + secs + " seconds");
            } catch (IOException e) {
                // This probably means that locking is enforced by the OS
                // and we were prevented from reading the file.
            }

            // This is an abnormal exit, so set an exit code.
            System.exit(1);
        }

        // Simulate a real application by sleeping for 10 seconds.
        System.out.println("Starting...");
        Thread.sleep(10000);
        System.out.println("Exiting.");
    } finally {
        // Always release the lock and close the file
        // Closing the RandomAccessFile also closes its FileChannel.
        if (lock != null && lock.isValid())
            lock.release();
        if (file != null)
            file.close();
    }
}

From source file:SenBench.java

public static void main(String[] args) {
    try {/*  w  w w .  jav  a  2  s . co  m*/
        if (args.length == 0) {
            System.out.println("usage: java SenBench file [file ..]");
            System.exit(2);
        }

        StringTagger tagger = StringTagger.getInstance(Locale.JAPANESE);

        long processed = 0;
        long nbytes = 0;
        long nchars = 0;

        long start = System.currentTimeMillis();
        for (int a = 0; a < args.length; a++) {
            String text = "";
            try {
                RandomAccessFile raf = new RandomAccessFile(args[a], "r");
                byte[] buf = new byte[(int) raf.length()];
                raf.readFully(buf);
                raf.close();
                text = new String(buf, encoding);
                nbytes += buf.length;
                nchars += text.length();
            } catch (IOException ioe) {
                log.error(ioe);
                continue;
            }

            long s_start = System.currentTimeMillis();
            for (int c = 0; c < repeat; c++)
                doWork(tagger, text);
            long s_end = System.currentTimeMillis();
            processed += (s_end - s_start);
        }
        long end = System.currentTimeMillis();
        System.out.println("number of files: " + args.length);
        System.out.println("number of repeat: " + repeat);
        System.out.println("number of bytes: " + nbytes);
        System.out.println("number of chars: " + nchars);
        System.out.println("total time elapsed: " + (end - start) + " msec.");
        System.out.println("analysis time: " + (processed) + " msec.");
    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:BridgeBasics.java

public static void main(String args[]) throws Exception {
    RServices rs = DirectJNI.getInstance().getRServices();
    rs.consoleSubmit("k=function(x){x*5}");

    System.out//from   w w w.  ja v a 2 s.c  o  m
            .println("////////////////////////////////" + rs.callAndConvert(new RFunctionObjectName("k"), 45));

    //rs.putAndAssign(new RUnknown(o.getValue()), "b");
    //System.out.println("-------------------------------"+rs.print("h"));

    /*
            
    RServices rs =
       ServerManager.createR("toto"); 
            
       RObject ro1 = 
    rs.getObject("structure(list(1,2), caption = \"foo\")");
       RObject ro2 = 
    rs.getReference("structure(list(1,2), caption = \"foo\")");
       System.out.println(rs.callAndConvert("str", ro1));
       System.out.println(rs.callAndConvert("str", ro2));
            
            
    rs.die();
            
    if (true) return;
    */

    rs = DirectJNI.getInstance().getRServices();
    GDDevice device = rs.newDevice(400, 400);
    rs.consoleSubmit("plot(pressure)");
    System.out.println(rs.getStatus());
    byte[] buffer = device.getPng();
    RandomAccessFile raf = new RandomAccessFile("c:/te.png", "rw");
    raf.setLength(0);
    raf.write(buffer);
    raf.close();

    //rs.evaluate("x=2;y=8",2);

    /*
    RS3 s3=(RS3)rs.getReference("packageDescription('stats')");
    System.out.println("s="+Arrays.toString(s3.getClassAttribute()));
    s3.setClassAttribute(new String[] {s3.getClassAttribute()[0], "aaa"});
    rs.assignReference("f",s3);
    //rs.call("print",new RObjectName("f"));
    //System.out.println("log=" + rs.getStatus());
            
    rs.consoleSubmit("print(class(f))");
    System.out.println("log=" + rs.getStatus());
            
    RChar s = (RChar) rs.call("paste", new RChar("str1"), new RChar("str2"), new RNamedArgument("sep", new RChar(
    "--")));
    System.out.println("s=" + s);
    */

    System.exit(0);

}

From source file:MeCabBench.java

public static void main(String[] args) {
    try {//  w  ww  .ja  va2 s. co m
        if (args.length == 0) {
            System.out.println("usage: java MeCabBench file [file ..]");
            System.exit(2);
        }

        Tagger tagger = new Tagger(new String[] { "java", "-d", dicPath });

        long processed = 0;
        long nbytes = 0;
        long nchars = 0;

        long start = System.currentTimeMillis();
        for (int a = 0; a < args.length; a++) {
            String text = "";
            try {
                RandomAccessFile raf = new RandomAccessFile(args[a], "r");
                byte[] buf = new byte[(int) raf.length()];
                raf.readFully(buf);
                raf.close();
                text = new String(buf, encoding);
                nbytes += buf.length;
                nchars += text.length();
            } catch (IOException ioe) {
                log.error(ioe);
                continue;
            }

            long s_start = System.currentTimeMillis();
            for (int c = 0; c < repeat; c++)
                doWork(tagger, text);
            long s_end = System.currentTimeMillis();
            processed += (s_end - s_start);
        }
        long end = System.currentTimeMillis();
        System.out.println("number of files: " + args.length);
        System.out.println("number of repeat: " + repeat);
        System.out.println("number of bytes: " + nbytes);
        System.out.println("number of chars: " + nchars);
        System.out.println("total time elapsed: " + (end - start) + " msec.");
        System.out.println("analysis time: " + (processed) + " msec.");
    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:com.guns.media.tools.yuv.MediaTool.java

/**
 * @param args the command line arguments
 *///  www  .j ava 2s.co  m
public static void main(String[] args) throws IOException {

    try {
        Options options = getOptions();
        CommandLine cmd = null;
        int offset = 0;
        CommandLineParser parser = new GnuParser();
        cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            printHelp(options);
            exit(1);
        }

        if (cmd.hasOption("offset")) {
            offset = new Integer(cmd.getOptionValue("offset"));
        }
        int frame = new Integer(cmd.getOptionValue("f"));

        //  int scale = new Integer(args[2]);
        BufferedInputStream if1 = new BufferedInputStream(new FileInputStream(cmd.getOptionValue("if1")));
        BufferedInputStream if2 = new BufferedInputStream(new FileInputStream(cmd.getOptionValue("if2")));

        DataStorage.create(new Integer(cmd.getOptionValue("f")));

        int width = new Integer(cmd.getOptionValue("w"));
        int height = new Integer(cmd.getOptionValue("h"));
        LookUp.initSSYUV(width, height);
        //  int[][] frame1 = new int[width][height];
        //  int[][] frame2 = new int[width][height];
        int nRead;
        int fRead;
        byte[] data = new byte[width * height + ((width * height) / 2)];
        byte[] data1 = new byte[width * height + ((width * height) / 2)];
        int frames = 0;
        long start_ms = System.currentTimeMillis() / 1000L;
        long end_ms = start_ms;

        if (offset > 0) {
            if1.skip(((width * height + ((width * height) / 2)) * offset));
        } else if (offset < 0) {
            if2.skip(((width * height + ((width * height) / 2)) * (-1 * offset)));
        }

        if (cmd.hasOption("psnr")) {
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1) && frames < frame) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                PSNRCalculatorThread wt = new PSNRCalculatorThread(data_out, data1_out, frames, width, height);
                executor.execute(wt);
                frames++;

            }
            executor.shutdown();
            end_ms = System.currentTimeMillis();

            System.out.println("Frame Rate :" + frames * 1000 / ((end_ms - start_ms)));
            for (int i = 0; i < frames; i++) {
                System.out.println(
                        i + "," + 10 * Math.log10((255 * 255) / (DataStorage.getFrame(i) / (width * height))));

            }
        }
        if (cmd.hasOption("sub")) {

            RandomAccessFile raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw");

            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1)) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                ImageSubstractThread wt = new ImageSubstractThread(data_out, data1_out, frames, width, height,
                        raf);
                //wt.run();
                executor.execute(wt);

                frames++;

            }
            executor.shutdown();
            end_ms = System.currentTimeMillis() / 1000L;
            System.out.println("Frame Rate :" + frames / ((end_ms - start_ms)));

            raf.close();
        }
        if (cmd.hasOption("ss") && !cmd.getOptionValue("o").matches("-")) {

            RandomAccessFile raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw");

            // RandomAccessFile ra =  new RandomAccessFile(cmd.getOptionValue("o"), "rw");
            // MappedByteBuffer raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, ((width*height)+(width*height/2))*frame);
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1) && frames < frame) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                SidebySideImageThread wt = new SidebySideImageThread(data_out, data1_out, frames, width, height,
                        raf);
                // MPSidebySideImageThread wt = new MPSidebySideImageThread(data_out, data1_out, frames, width, height, ra);
                frames++;
                // wt.run();

                executor.execute(wt);
            }
            executor.shutdown();
            end_ms = System.currentTimeMillis() / 1000L;

            while (!executor.isTerminated()) {

            }

            raf.close();
        }
        if (cmd.hasOption("ss") && cmd.getOptionValue("o").matches("-")) {

            PrintStream stdout = new PrintStream(System.out);

            // RandomAccessFile ra =  new RandomAccessFile(cmd.getOptionValue("o"), "rw");
            // MappedByteBuffer raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, ((width*height)+(width*height/2))*frame);
            // ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1) && frames < frame) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                SidebySideImageThread wt = new SidebySideImageThread(data_out, data1_out, frames, width, height,
                        stdout);
                // MPSidebySideImageThread wt = new MPSidebySideImageThread(data_out, data1_out, frames, width, height, ra);
                frames++;
                // wt.run();

                wt.run();
            }

            end_ms = System.currentTimeMillis() / 1000L;
            System.out.println("Frame Rate :" + frames / ((end_ms - start_ms)));

            stdout.close();
        }
        if (cmd.hasOption("image")) {

            System.setProperty("java.awt.headless", "true");
            //ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1)) {

                if (frames == frame) {
                    byte[] data_out = data.clone();
                    byte[] data1_out = data1.clone();

                    Frame f1 = new Frame(data_out, width, height, Frame.YUV420);
                    Frame f2 = new Frame(data1_out, width, height, Frame.YUV420);
                    //       System.out.println(cmd.getOptionValue("o"));
                    ExtractImageThread wt = new ExtractImageThread(f1, frames,
                            cmd.getOptionValue("if1") + "frame1-" + cmd.getOptionValue("o"));
                    ExtractImageThread wt1 = new ExtractImageThread(f2, frames,
                            cmd.getOptionValue("if2") + "frame2-" + cmd.getOptionValue("o"));
                    //   executor.execute(wt);
                    executor.execute(wt);
                    executor.execute(wt1);
                }
                frames++;

            }
            executor.shutdown();
            //  executor.shutdown();
            end_ms = System.currentTimeMillis() / 1000L;
            System.out.println("Frame Rate :" + frames / ((end_ms - start_ms)));
        }

    } catch (ParseException ex) {
        Logger.getLogger(MediaTool.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.usc.qufd.Main.java

/**
 * The main method./*from  ww  w  . j a  v  a 2  s.c o  m*/
 *
 * @param args the arguments
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void main(String[] args) throws IOException {
    if (parseInputs(args) == false) {
        System.exit(-1); //The input files do not exist
    }

    /*
     * Parsing inputs: fabric & qasm file
     */
    PrintWriter outputFile;
    RandomAccessFile raf = null;
    String latencyPlaceHolder;
    if (RuntimeConfig.OUTPUT_TO_FILE) {
        latencyPlaceHolder = "Total Latency: " + Long.MAX_VALUE + " us" + System.lineSeparator();
        raf = new RandomAccessFile(outputFileAddr, "rws");
        //removing the old values in the file
        raf.setLength(0);
        //writing a place holder for the total latency
        raf.writeBytes(latencyPlaceHolder);
        raf.close();

        outputFile = new PrintWriter(new BufferedWriter(new FileWriter(outputFileAddr, true)), true);
    } else { //writing to stdout
        outputFile = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true);
    }
    /* parsing the input*/
    layout = LayoutParser.parse(pmdFileAddr);
    qasm = QASMParser.QASMParser(qasmFileAddr, layout);

    long totalLatency = qufd(outputFile);

    if (RuntimeConfig.OUTPUT_TO_FILE) {
        outputFile.close();
        //Over writing the place holder with the actual latency
        String latencyActual = "Total Latency: " + totalLatency + " " + layout.getTimeUnit();
        latencyActual = StringUtils.rightPad(latencyActual,
                latencyPlaceHolder.length() - System.lineSeparator().length());
        raf = new RandomAccessFile(outputFileAddr, "rws");
        //Writing to the top of a file
        raf.seek(0);
        //writing the actual total latency in the at the top of the output file
        raf.writeBytes(latencyActual + System.lineSeparator());
        raf.close();
    } else {
        outputFile.flush();
        System.out.println("Total Latency: " + totalLatency + " " + layout.getTimeUnit());
    }

    if (RuntimeConfig.VERBOSE) {
        System.out.println("Done.");
    }
    outputFile.close();
}