Example usage for java.io RandomAccessFile close

List of usage examples for java.io RandomAccessFile close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this random access file stream and releases any system resources associated with the stream.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    RandomAccessFile fh1 = new RandomAccessFile("a.txt", "r");
    RandomAccessFile fh2 = new RandomAccessFile("b.txt", "r");
    long filesize1 = fh1.length();
    long filesize2 = fh2.length();
    // allocate two buffers large enough to hold entire files
    int bufsize = (int) Math.min(filesize1, filesize2);
    byte[] buffer1 = new byte[bufsize];
    byte[] buffer2 = new byte[bufsize];

    fh1.readFully(buffer1, 0, bufsize);/*from  w  w  w .j av a 2  s. c om*/
    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;
        }
    }
    fh1.close();
    fh2.close();
}

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

/**
 * The main method.//from w ww .ja  v  a 2s. 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();
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    File aFile = new File("C:/test.bin");
    RandomAccessFile ioFile = new RandomAccessFile(aFile, " rw");

    FileChannel ioChannel = ioFile.getChannel();
    final int PRIMESREQUIRED = 10;
    long[] primes = new long[PRIMESREQUIRED];

    int index = 0;
    final long REPLACEMENT = 999999L;

    final int PRIMECOUNT = (int) ioChannel.size() / 8;
    MappedByteBuffer buf = ioChannel.map(FileChannel.MapMode.READ_WRITE, 0L, ioChannel.size()).load();
    ioChannel.close();/* w w  w  .  jav  a 2s .c  o m*/

    for (int i = 0; i < PRIMESREQUIRED; i++) {
        index = 8 * (int) (PRIMECOUNT * Math.random());
        primes[i] = buf.getLong(index);
        buf.putLong(index, REPLACEMENT);
    }

    for (long prime : primes) {
        System.out.printf("%12d", prime);
    }
    ioFile.close();
}

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

/**
 * @param args the command line arguments
 *///from  ww  w .  ja v  a 2s.c  om
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:Diff.java

public static void main(String args[]) {
    RandomAccessFile fh1 = null;
    RandomAccessFile fh2 = null;/*from  w w w.j a  v  a  2s  .  co  m*/
    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: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  .j a v 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:Main.java

public static void append(String fileName, byte[] bytes) throws Exception {
    File f = new File(fileName);
    long fileLength = f.length();
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.seek(fileLength);//w w w . j  a v  a  2s  . c  o m
    raf.write(bytes);
    raf.close();
}

From source file:Main.java

public static void append(String fileName, String text) throws Exception {
    File f = new File(fileName);
    long fileLength = f.length();
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.seek(fileLength);/*from  ww  w.  j a  v  a  2s.c  om*/
    raf.writeBytes(text);
    raf.close();
}

From source file:Main.java

public static boolean createEmptyFile(String path, long size) throws IOException {
    File file = new File(path);
    File parent = file.getParentFile();
    parent.mkdirs();//  ww  w.  ja va 2 s  .  c  o  m
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    raf.setLength(size);
    raf.close();
    return true;
}

From source file:Main.java

public static void closeRandomAccessFile(RandomAccessFile f) {
    if (f != null) {
        try {//from   ww  w.  jav  a  2 s.  co m
            f.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}