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:jm.web.Archivo.java

public String getArchivoXml(String path, String tabla, String clave, String campoNombre, String campo) {
    this._archivoNombre = "";
    try {/*from  w  ww  .j  a v  a  2s . co m*/
        ResultSet res = this.consulta("select * from " + tabla + " where clave_acceso='" + clave + "'   ;");
        if (res.next()) {
            this._archivoNombre = res.getString(campoNombre) != null ? res.getString(campoNombre) : "";
            if (this._archivoNombre.compareTo("") != 0) {
                try {
                    this._archivo = new File(path, this._archivoNombre);
                    if (!this._archivo.exists()) {
                        //byte[] bytes = (res.getString(campoBytea)!=null) ? res.getBytes(campoBytea) : null;
                        RandomAccessFile archivo = new RandomAccessFile(path + this._archivoNombre + ".xml",
                                "rw");
                        archivo.writeBytes(campo);
                        archivo.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            res.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this._archivoNombre;
}

From source file:jp.andeb.obbutil.ObbUtilMain.java

private static boolean doRemove(String[] args) {
    if (args.length != 1) {
        printUsage(PROGNAME);//from  ww w  .j  ava2s  . c o m
        return false;
    }
    final File targetFile = new File(args[0]);
    final RandomAccessFile targetRaFile;
    try {
        targetRaFile = new RandomAccessFile(targetFile, "rw");
    } catch (FileNotFoundException e) {
        System.err.println("????: " + targetFile.getPath());
        return false;
    }
    try {
        final ObbInfoV1 obbInfo;
        try {
            obbInfo = ObbInfoV1.fromFile(targetRaFile);
        } catch (IOException e) {
            System.err
                    .println("????????: " + targetFile.getPath());
            return false;
        } catch (NotObbException e) {
            System.err.println(
                    "? OBB ???????: " + targetFile.getPath());
            return false;
        }

        final ByteBuffer obbInfoBytes = obbInfo.toBytes();
        targetRaFile.setLength(targetRaFile.length() - obbInfoBytes.remaining());
    } catch (IOException e) {
        System.err.println("OBB ??????: " + targetFile.getPath());
        return false;
    } finally {
        try {
            targetRaFile.close();
        } catch (IOException e) {
            System.err.println("OBB ??????: " + targetFile.getPath());
            return false;
        }
    }

    System.err.println("OBB ???????: " + targetFile.getPath());
    return true;
}

From source file:WordList.java

public static void writeWords(String filename, String[] words) throws IOException {
    // Open the file for read/write access ("rw"). We only need to write,
    // but have to request read access as well
    RandomAccessFile f = new RandomAccessFile(filename, "rw");

    // This array will hold the positions of each word in the file
    long wordPositions[] = new long[words.length];

    // Reserve space at the start of the file for the wordPositions array
    // and the length of that array. 4 bytes for length plus 8 bytes for
    // each long value in the array.
    f.seek(4L + (8 * words.length));/*ww w. ja  v  a  2 s.c  om*/

    // Now, loop through the words and write them out to the file,
    // recording the start position of each word. Note that the
    // text is written in the UTF-8 encoding, which uses 1, 2, or 3 bytes
    // per character, so we can't assume that the string length equals
    // the string size on the disk. Also note that the writeUTF() method
    // records the length of the string so it can be read by readUTF().
    for (int i = 0; i < words.length; i++) {
        wordPositions[i] = f.getFilePointer(); // record file position
        f.writeUTF(words[i]); // write word
    }

    // Now go back to the beginning of the file and write the positions
    f.seek(0L); // Start at beginning
    f.writeInt(wordPositions.length); // Write array length
    for (int i = 0; i < wordPositions.length; i++)
        // Loop through array
        f.writeLong(wordPositions[i]); // Write array element
    f.close(); // Close the file when done.
}

From source file:com.adaptris.fs.NioWorkerTest.java

@Test
public void testLockWhileReading() throws Exception {
    FsWorker worker = createWorker();//from w  w w.ja  v a  2 s  .c  o  m
    File f = File.createTempFile(this.getClass().getSimpleName(), "");
    f.delete();
    try {
        worker.put(BYTES, f);

        RandomAccessFile raf = new RandomAccessFile(f, "rwd");
        FileLock lock = raf.getChannel().lock();
        try {
            worker.get(f);
            fail();
        } catch (FsException expected) {
            assertEquals(OverlappingFileLockException.class, expected.getCause().getClass());
        }
        lock.release();
        raf.close();
        worker.get(f);
    } finally {
        FileUtils.deleteQuietly(f);
    }
}

From source file:com.polarion.pso.license.FetchUserLicenseTypeServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    ISecurityService securityService = (ISecurityService) PlatformContext.getPlatform()
            .lookupService(ISecurityService.class);
    ITrackerService trackerService = (ITrackerService) PlatformContext.getPlatform()
            .lookupService(ITrackerService.class);

    String userId = securityService.getCurrentUser();
    String userName = trackerService.getTrackerUser(userId).getName();

    long cutoff = System.currentTimeMillis() - (1000);
    File directory = new File("./logs/main");

    FileFilter wcFilter = new WildcardFileFilter("log4j-licensing-*.log");
    AgeFileFilter ageFilter = new AgeFileFilter(cutoff);
    FileFilter andFilter = new org.apache.commons.io.filefilter.AndFileFilter((IOFileFilter) ageFilter,
            (IOFileFilter) wcFilter);// ww w . j a  v a  2  s .  c  o  m

    Collection<File> matches = FileUtils.listFiles(directory, (IOFileFilter) andFilter, null);

    if (!matches.isEmpty()) {

        File myFile = matches.iterator().next();
        RandomAccessFile licFile = new RandomAccessFile(myFile, "r");

        // Read the last 1024 bytes
        Long fileLength = licFile.length();
        Long offSet = fileLength - 1024;
        byte[] bStr = new byte[1024];
        licFile.seek(offSet);
        licFile.read(bStr);
        licFile.close();

        String logString = new java.lang.String(bStr);

        String[] lineArray = logString.split("\n");

        String searchString = "INFO  PolarionLicensing  - User \'" + userId + "\' logged in";
        Boolean found = false;
        Integer size = lineArray.length - 1;
        String licType = directory.toString();

        for (int i = size; i >= 0; i--) {
            String line = lineArray[i];
            if (line.contains(searchString) && found == false) {
                found = true;
                i = -1;
                Integer startIndex = line.indexOf(searchString) + searchString.length() + 6;
                licType = line.substring(startIndex);
                licType = licType.replace("\r", "");
                licType = licType.trim();
            }
        }

        req.setAttribute("userId", userName);
        req.setAttribute("licType", licType);
    } else {
        req.setAttribute("userId", userName);
        req.setAttribute("licType", "Not Found");
    }

    getServletContext().getRequestDispatcher("/currentUserLicenseType.jsp").forward(req, resp);
}

From source file:com.gh4a.utils.HttpImageGetter.java

private static Bitmap getBitmap(final File image, int width, int height) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    RandomAccessFile file = null;

    try {//from   www  . j a v  a  2 s. c  o m
        file = new RandomAccessFile(image.getAbsolutePath(), "r");
        FileDescriptor fd = file.getFD();

        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFileDescriptor(fd, null, options);

        int scale = 1;
        while (options.outWidth >= width || options.outHeight >= height) {
            options.outWidth /= 2;
            options.outHeight /= 2;
            scale *= 2;
        }

        options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inSampleSize = scale;

        return BitmapFactory.decodeFileDescriptor(fd, null, options);
    } catch (IOException e) {
        return null;
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                // ignored
            }
        }
    }
}

From source file:IntergrationTest.OCSPIntegrationTest.java

@Before
public void setUp() throws Exception {
    OCSP_URL = new URI("http://localhost:" + serverPort + "/verify-mocked-good");
    OCSP_MODE_URL = new URI("http://localhost:" + serverPort + "/set-response-mode");
    RandomAccessFile raf = new RandomAccessFile("certs/client/client.cer.pem", "r");
    byte[] buf = new byte[(int) raf.length()];
    raf.readFully(buf);//from   w  ww.  j av  a2  s .c om
    raf.close();
    clientCert = readPemCert(buf);
    MatcherAssert.assertThat(clientCert, CoreMatchers.notNullValue());
    issuerCert = getX509Certificate(httpGetBin(getIssuerCertURL(clientCert), true));
    MatcherAssert.assertThat(issuerCert, CoreMatchers.notNullValue());
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestFSEditLogLoader.java

/**
 * Truncate the given file to the given length
 *///from w ww . jav a  2  s.  c o  m
private void truncateFile(File logFile, long newLength) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(logFile, "rw");
    raf.setLength(newLength);
    raf.close();
}

From source file:org.apache.flume.channel.file.Serialization.java

/**
 * Copy a file using a 64K size buffer. This method will copy the file and
 * then fsync to disk// w  w  w  . j ava  2  s  . co  m
 * @param from File to copy - this file should exist
 * @param to Destination file - this file should not exist
 * @return true if the copy was successful
 */
public static boolean copyFile(File from, File to) throws IOException {
    Preconditions.checkNotNull(from, "Source file is null, file copy failed.");
    Preconditions.checkNotNull(to, "Destination file is null, " + "file copy failed.");
    Preconditions.checkState(from.exists(), "Source file: " + from.toString() + " does not exist.");
    Preconditions.checkState(!to.exists(), "Destination file: " + to.toString() + " unexpectedly exists.");

    BufferedInputStream in = null;
    RandomAccessFile out = null; //use a RandomAccessFile for easy fsync
    try {
        in = new BufferedInputStream(new FileInputStream(from));
        out = new RandomAccessFile(to, "rw");
        byte[] buf = new byte[FILE_COPY_BUFFER_SIZE];
        int total = 0;
        while (true) {
            int read = in.read(buf);
            if (read == -1) {
                break;
            }
            out.write(buf, 0, read);
            total += read;
        }
        out.getFD().sync();
        Preconditions.checkState(total == from.length(),
                "The size of the origin file and destination file are not equal.");
        return true;
    } catch (Exception ex) {
        LOG.error("Error while attempting to copy " + from.toString() + " to " + to.toString() + ".", ex);
        Throwables.propagate(ex);
    } finally {
        Throwable th = null;
        try {
            if (in != null) {
                in.close();
            }
        } catch (Throwable ex) {
            LOG.error("Error while closing input file.", ex);
            th = ex;
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException ex) {
            LOG.error("Error while closing output file.", ex);
            Throwables.propagate(ex);
        }
        if (th != null) {
            Throwables.propagate(th);
        }
    }
    // Should never reach here.
    throw new IOException("Copying file: " + from.toString() + " to: " + to.toString() + " may have failed.");
}

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

@Test
public void testInitForWritingThenClose() throws IOException {
    JournalFile jf1 = new JournalFile(theFile);
    jf1.initForWriting(new UUID());
    assertThat(jf1.isWriteMode(), is(true));
    assertThat(jf1.isOpen(), is(true));/* w w w.  j  av a 2s. c  o m*/
    assertThat(jf1.getFilePosition(), is((long) JournalFile.HEADER_SIZE));
    jf1.close();

    assertThat(jf1.isOpen(), is(false));

    RandomAccessFile raFile = new RandomAccessFile(theFile, "rw");
    assertThat(raFile.readInt(), is(JournalFile.VERSION));
    assertThat(Utils.readUuidFromFile(raFile), is(jf1.getId()));
    assertThat(raFile.readLong(), is(0L));
    raFile.close();
}