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:edu.mbl.jif.imaging.mmtiff.MultipageTiffReader.java

private void createFileChannel() throws FileNotFoundException, IOException {
    raFile_ = new RandomAccessFile(file_, "rw");
    fileChannel_ = raFile_.getChannel();
}

From source file:net.sf.jasperreports.engine.util.JRSwapFile.java

/**
 * Creates a swap file.//from   w w w. j  a v a  2 s . c om
 * 
 * The file name is generated automatically.
 * 
 * @param jasperReportsContext the JasperReportsContext to read configuration from.
 * @param directory the directory where the file should be created.
 * @param blockSize the size of the blocks allocated by the swap file
 * @param minGrowCount the minimum number of blocks by which the swap file grows when full
 */
public JRSwapFile(JasperReportsContext jasperReportsContext, String directory, int blockSize,
        int minGrowCount) {
    try {
        String filename = "swap_" + System.identityHashCode(this) + "_" + System.currentTimeMillis();
        swapFile = new File(directory, filename);
        if (log.isDebugEnabled()) {
            log.debug("Creating swap file " + swapFile.getPath());
        }
        boolean fileExists = swapFile.exists();

        boolean deleteOnExit = JRPropertiesUtil.getInstance(jasperReportsContext)
                .getBooleanProperty(PROPERTY_DELETE_ON_EXIT);
        if (deleteOnExit) {
            swapFile.deleteOnExit();
        }

        file = new RandomAccessFile(swapFile, "rw");//FIXME to this lazily?

        this.blockSize = blockSize;
        this.minGrowCount = minGrowCount;
        freeBlocks = new LongQueue(minGrowCount);

        if (fileExists) {
            file.setLength(0);
            if (log.isDebugEnabled()) {
                log.debug("Swap file " + swapFile.getPath() + " exists, truncating");
            }
        }
    } catch (FileNotFoundException e) {
        throw new JRRuntimeException(e);
    } catch (IOException e) {
        throw new JRRuntimeException(e);
    }
}

From source file:cc.arduino.utils.network.FileDownloader.java

private void downloadFile(boolean noResume) throws InterruptedException {
    RandomAccessFile file = null;

    try {/*w w w . j  a  va  2s. c o  m*/
        // Open file and seek to the end of it
        file = new RandomAccessFile(outputFile, "rw");
        initialSize = file.length();

        if (noResume && initialSize > 0) {
            // delete file and restart downloading
            Files.delete(outputFile.toPath());
            initialSize = 0;
        }

        file.seek(initialSize);

        setStatus(Status.CONNECTING);

        Proxy proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(downloadUrl.toURI());
        if ("true".equals(System.getProperty("DEBUG"))) {
            System.err.println("Using proxy " + proxy);
        }

        HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(proxy);
        connection.setRequestProperty("User-agent", userAgent);
        if (downloadUrl.getUserInfo() != null) {
            String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes()));
            connection.setRequestProperty("Authorization", auth);
        }

        connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
        connection.setConnectTimeout(5000);
        setDownloaded(0);

        // Connect
        connection.connect();
        int resp = connection.getResponseCode();

        if (resp == HttpURLConnection.HTTP_MOVED_PERM || resp == HttpURLConnection.HTTP_MOVED_TEMP) {
            URL newUrl = new URL(connection.getHeaderField("Location"));

            proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(newUrl.toURI());

            // open the new connnection again
            connection = (HttpURLConnection) newUrl.openConnection(proxy);
            connection.setRequestProperty("User-agent", userAgent);
            if (downloadUrl.getUserInfo() != null) {
                String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes()));
                connection.setRequestProperty("Authorization", auth);
            }

            connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
            connection.setConnectTimeout(5000);

            connection.connect();
            resp = connection.getResponseCode();
        }

        if (resp < 200 || resp >= 300) {
            throw new IOException("Received invalid http status code from server: " + resp);
        }

        // Check for valid content length.
        long len = connection.getContentLength();
        if (len >= 0) {
            setDownloadSize(len);
        }
        setStatus(Status.DOWNLOADING);

        synchronized (this) {
            stream = connection.getInputStream();
        }
        byte buffer[] = new byte[10240];
        while (status == Status.DOWNLOADING) {
            int read = stream.read(buffer);
            if (read == -1)
                break;

            file.write(buffer, 0, read);
            setDownloaded(getDownloaded() + read);

            if (Thread.interrupted()) {
                file.close();
                throw new InterruptedException();
            }
        }

        if (getDownloadSize() != null) {
            if (getDownloaded() < getDownloadSize())
                throw new Exception("Incomplete download");
        }
        setStatus(Status.COMPLETE);
    } catch (InterruptedException e) {
        setStatus(Status.CANCELLED);
        // lets InterruptedException go up to the caller
        throw e;

    } catch (SocketTimeoutException e) {
        setStatus(Status.CONNECTION_TIMEOUT_ERROR);
        setError(e);

    } catch (Exception e) {
        setStatus(Status.ERROR);
        setError(e);

    } finally {
        IOUtils.closeQuietly(file);

        synchronized (this) {
            IOUtils.closeQuietly(stream);
        }
    }
}

From source file:com.notifier.desktop.Main.java

private static boolean getExclusiveExecutionLock() throws IOException {
    File lockFile = new File(OperatingSystems.getWorkDirectory(), Application.ARTIFACT_ID + ".lock");
    Files.createParentDirs(lockFile);
    lockFile.createNewFile();/*from w ww  .j av  a 2s . com*/
    final RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile, "rw");
    final FileChannel fileChannel = randomAccessFile.getChannel();
    final FileLock fileLock = fileChannel.tryLock();
    if (fileLock == null) {
        Closeables.closeQuietly(fileChannel);
        Closeables.closeQuietly(randomAccessFile);
        return false;
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                fileLock.release();
            } catch (IOException e) {
                System.err.println("Error releasing file lock");
                e.printStackTrace(System.err);
            } finally {
                Closeables.closeQuietly(fileChannel);
                Closeables.closeQuietly(randomAccessFile);
            }
        }
    });
    return true;
}

From source file:de.rwhq.io.rm.FileResourceManager.java

/**
 * Generic private initializer that takes the random access file and initializes the I/O channel and locks it for
 * exclusive use by this instance./*from   www  .  j a  v a  2  s  .  c  o  m*/
 * <p/>
 * from minidb
 *
 * @param file
 *       The random access file representing the index.
 * @throws IOException
 *       Thrown, when the I/O channel could not be opened.
 */
private void initIOChannel(final File file) throws IOException {
    handle = new RandomAccessFile(file, "rw");

    // Open the channel. If anything fails, make sure we close it again
    for (int i = 1; i <= 5; i++) {
        try {
            ioChannel = handle.getChannel();
            if (doLock) {
                LOG.debug("trying to aquire lock ...");
                ioChannel.lock();
                LOG.debug("lock aquired");
                break;
            }
        } catch (Throwable t) {
            LOG.warn("File " + file.getAbsolutePath() + " could not be locked in attempt " + i + ".");

            try {
                Thread.sleep(200);
            } catch (InterruptedException ignored) {
            }

            // propagate the exception
            if (i >= 5) {
                close();
                throw new IOException("An error occured while opening the index: ", t);
            }
        }
    }
}

From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffReader.java

public static boolean isMMMultipageTiff(String directory) throws IOException {
    File dir = new File(directory);
    File[] children = dir.listFiles();
    File testFile = null;/* w  w w .ja v  a2 s.  co m*/
    for (File child : children) {
        if (child.isDirectory()) {
            File[] grandchildren = child.listFiles();
            for (File grandchild : grandchildren) {
                if (grandchild.getName().endsWith(".tif")) {
                    testFile = grandchild;
                    break;
                }
            }
        } else if (child.getName().endsWith(".tif") || child.getName().endsWith(".TIF")) {
            testFile = child;
            break;
        }
    }
    if (testFile == null) {
        throw new IOException("Unexpected file structure: is this an MM dataset?");
    }
    RandomAccessFile ra;
    try {
        ra = new RandomAccessFile(testFile, "r");
    } catch (FileNotFoundException ex) {
        ReportingUtils.logError(ex);
        return false;
    }
    FileChannel channel = ra.getChannel();
    ByteBuffer tiffHeader = ByteBuffer.allocate(36);
    ByteOrder bo;
    channel.read(tiffHeader, 0);
    char zeroOne = tiffHeader.getChar(0);
    if (zeroOne == 0x4949) {
        bo = ByteOrder.LITTLE_ENDIAN;
    } else if (zeroOne == 0x4d4d) {
        bo = ByteOrder.BIG_ENDIAN;
    } else {
        throw new IOException("Error reading Tiff header");
    }
    tiffHeader.order(bo);
    int summaryMDHeader = tiffHeader.getInt(32);
    channel.close();
    ra.close();
    if (summaryMDHeader == MultipageTiffWriter.SUMMARY_MD_HEADER) {
        return true;
    }
    return false;
}

From source file:com.skin.generator.action.UploadTestAction.java

/**
 * @throws IOException/*from ww w.  j  av a2 s  .  co  m*/
 * @throws ServletException
 */
@UrlPattern("/upload/test2.html")
public void test2() throws IOException, ServletException {
    logger.info("method: " + this.request.getMethod() + " " + this.request.getRequestURI() + " "
            + this.request.getQueryString());

    /**
     * cross domain support
     */
    this.doOptions(this.request, this.response);

    /**
      * preflight
     */
    if (this.request.getMethod().equalsIgnoreCase("OPTIONS")) {
        logger.info("options: " + this.request.getHeader("Origin"));
        return;
    }

    String home = this.servletContext.getRealPath("/WEB-INF/tmp");
    Map<String, Object> result = new HashMap<String, Object>();
    RandomAccessFile raf = null;
    InputStream inputStream = null;

    try {
        Map<String, Object> map = this.parse(this.request);
        int start = Integer.parseInt((String) map.get("start"));
        int end = Integer.parseInt((String) map.get("end"));
        int length = Integer.parseInt((String) map.get("length"));
        FileItem fileItem = (FileItem) map.get("fileData");

        inputStream = fileItem.getInputStream();
        raf = new RandomAccessFile(new File(home, fileItem.getName()), "rw");
        raf.seek(start);
        String partMd5 = copy(inputStream, raf, 4096);

        if (end >= length) {
            String fileMd5 = Hex.encode(Digest.md5(new File(home, fileItem.getName())));
            result.put("fileMd5", fileMd5);
        }

        result.put("status", 200);
        result.put("message", "??");
        result.put("start", end);
        result.put("partMD5", partMd5);
        JsonUtil.callback(this.request, this.response, result);
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        result.put("status", 500);
        result.put("message", "?");
        JsonUtil.callback(this.request, this.response, result);
        return;
    } finally {
        close(raf);
        close(inputStream);
    }
}

From source file:org.red5.server.service.ShutdownServer.java

/**
 * Starts internal server listening for shutdown requests.
 *//*from  ww  w  . ja v a 2 s  .c o  m*/
public void start() {
    // dump to stdout
    System.out.printf("Token: %s%n", token);
    // write out the token to a file so that red5 may be shutdown external to this VM instance.
    try {
        // delete existing file
        Files.deleteIfExists(Paths.get(shutdownTokenFileName));
        // write to file
        Path path = Files.createFile(Paths.get(shutdownTokenFileName));
        File tokenFile = path.toFile();
        RandomAccessFile raf = new RandomAccessFile(tokenFile, "rws");
        raf.write(token.getBytes());
        raf.close();
    } catch (Exception e) {
        log.warn("Exception handling token file", e);
    }
    while (!shutdown.get()) {
        try (ServerSocket serverSocket = new ServerSocket(port);
                Socket clientSocket = serverSocket.accept();
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));) {
            log.info("Connected - local: {} remote: {}", clientSocket.getLocalSocketAddress(),
                    clientSocket.getRemoteSocketAddress());
            String inputLine = in.readLine();
            if (inputLine != null && token.equals(inputLine)) {
                log.info("Shutdown request validated using token");
                out.println("Ok");
                shutdownOrderly();
            } else {
                out.println("Bye");
            }
        } catch (BindException be) {
            log.error("Cannot bind to port: {}, ensure no other instances are bound or choose another port",
                    port, be);
            shutdownOrderly();
        } catch (IOException e) {
            log.warn("Exception caught when trying to listen on port {} or listening for a connection", port,
                    e);
        }
    }
}

From source file:mitm.common.util.RewindableInputStream.java

private void storeInBuffer(byte b) throws IOException {
    if (byteBuffer != null) {
        byteBuffer.write(b);// ww  w .  ja v a 2 s .  c  om

        if (byteBuffer.size() > threshold) {
            /*
             * Threshold exceeded. Create a temp file and 
             */
            file = File.createTempFile(FileConstants.TEMP_FILE_PREFIX, null);

            randomAccessFile = new RandomAccessFile(file, "rw");

            /*
             * wrap the randomAccessFile into a buffer to speedup the writing
             */
            fileWriteBuffer = new BufferedOutputStream(new RandomAccessFileOutputStream(randomAccessFile));

            /*
             * Copy the existing buffer and make buffer null.
             */
            fileWriteBuffer.write(byteBuffer.getBuffer(), 0, byteBuffer.size());

            byteBuffer = null;
        }
    } else {
        fileWriteBuffer.write(b);
    }
}

From source file:com.bittorrent.mpetazzoni.client.storage.FileStorage.java

/** Move the partial file to its final location.
 *///  ww w. j  av a2  s .com
@Override
public synchronized void finish() throws IOException {
    logger.debug("Closing file channel to " + this.current.getName() + " (download complete).");
    if (this.channel.isOpen()) {
        this.channel.force(true);
    }

    // Nothing more to do if we're already on the target file.
    if (this.isFinished()) {
        return;
    }

    this.raf.close();
    FileUtils.deleteQuietly(this.target);
    FileUtils.moveFile(this.current, this.target);

    logger.debug("Re-opening torrent byte storage at {}.", this.target.getAbsolutePath());

    this.raf = new RandomAccessFile(this.target, "rw");
    this.raf.setLength(this.size);
    this.channel = this.raf.getChannel();
    this.current = this.target;

    FileUtils.deleteQuietly(this.partial);
    logger.info("Moved torrent data from {} to {}.", this.partial.getName(), this.target.getName());
}