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:eu.trentorise.smartcampus.feedback.test.TestFeedbackManagers.java

private void writeTestFile(byte[] data) throws IOException {
    RandomAccessFile f = new RandomAccessFile("src/test/resources/android_copy.jpg", "rw");
    f.write(data);/*  ww  w . j  a v a  2s  .  c o m*/
    f.close();
}

From source file:AutoDJ.metaReader.OggIndexer.java

/**
 * open the file, jump to the comment header and put it in the buffer,
 * then populate the internal hashmap of metadata
 * //from   w ww  .j a  v  a 2 s .c o  m
 * @param String path
 */
public void readFile(String path) throws Exception {
    audioFile = new File(path);
    raf = new RandomAccessFile(audioFile, "r");

    // we need to read that in order to know where to start looking
    readIdentificationHeader();

    // skip over the parts we don't care about
    readCommentHeader();

    int venLen = getIntFromBuff();
    raf.skipBytes(venLen); // skip over the vendor string (always the same)

    numberVorbisComments = getIntFromBuff();
    vorbisComments = new HashMap<String, String>();

    for (int i = 0; i < numberVorbisComments; i++) {
        int readLength = getIntFromBuff();
        long newFilePos = raf.getFilePointer() + readLength;
        String content = "";

        // take care of pages spanning more than one packet
        while (concatNext && (newFilePos - headerStart) >= two16) {
            long packetEnd = headerStart + two16;
            int readLengthShort = readLength - ((int) (newFilePos - packetEnd));

            byte[] contentFirst = new byte[readLengthShort];
            raf.read(contentFirst);
            content += new String(contentFirst);

            concatNext = false;

            // now comes another ogg header...
            //System.out.println("looking for new header at "+raf.getFilePointer() );
            readOggHeader();
        }

        byte[] contentRest = new byte[readLength];
        raf.read(contentRest);

        content += new String(contentRest);
        addToMap(content.getBytes());
    }
}

From source file:com.ibm.sbt.test.lib.MockSerializer.java

public void writeData(String data) throws IOException {
    File file = getFile(true);//from w  w w . j a v  a 2s.co m
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    // Seek to end of file
    System.out.println("Writing Record @" + file.length() + " in " + file.getAbsolutePath());
    raf.seek((file.length() - "\n</responses>".length()));

    raf.write(data.getBytes("UTF-8"));
    raf.write("\n</responses>".getBytes("UTF-8"));

}

From source file:interfazGrafica.frmMoverRFC.java

public void mostrarPDF() {
    String curp = "";
    curp = txtCapturaCurp.getText();/*from  w  w w.ja  v a 2  s  . c  om*/
    ArrayList<DocumentoRFC> Docs = new ArrayList<>();
    DocumentoRFC sigExp;
    DocumentoRFC temporal;
    RFCescaneado tempo = new RFCescaneado();

    //tempo.borrartemporal();
    sigExp = expe.obtenerArchivosExp();
    Nombre_Archivo = sigExp.getNombre();
    nombreArchivo.setText(Nombre_Archivo);

    if (Nombre_Archivo != "") {
        doc = sigExp;
        System.out.println("Obtuvo el nombre del archivo.");
        System.out.println(doc.ruta + doc.nombre);
        String file = "C:\\escaneos\\Local\\Temporal\\" + doc.nombre;
        File arch = new File(file);
        System.out.println("Encontr el siguiente archivo:");
        System.out.println(file);
        System.out.println("");
        if (arch.exists()) {
            System.out.println("El archivo existe");
        }
        try {
            System.out.println("Entr al try");
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            System.out.println("Reconoc el archivo" + file);
            FileChannel channel = raf.getChannel();
            System.out.println("Se abrio el canal");
            ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            System.out.println("Channel map");
            PDFFile pdffile = new PDFFile(buf);
            System.out.println("Creando un pdf file");
            PDFPage page = pdffile.getPage(0);
            System.out.println("Obteniendo la pagina con " + 0);

            panelpdf2.showPage(page);
            System.out.println("mostrando el panel pdf2");
            repaint();
            System.gc();

            buf.clear();
            raf.close();

            System.gc();

        } catch (Exception ioe) {
            JOptionPane.showMessageDialog(null, "Error al abrir el archivo");
            ioe.printStackTrace();
        }

    }
    // tempo.borrartemporal();
}

From source file:com.apporiented.hermesftp.streams.RafOutputStream.java

private RandomAccessFile getRaf() throws IOException {
    if (raf == null) {
        raf = new RandomAccessFile(file, "rw");
        if (offset > 0) {
            raf.seek(offset);/*from  w  w  w. j a  va 2  s. co  m*/
        } else if (offset < 0) {
            raf.seek(raf.length());
        }
    }
    return raf;
}

From source file:com.meidusa.venus.benchmark.FileLineRandomData.java

@Override
public void init() throws InitialisationException {
    try {/*from   w w w  . j a v a 2  s .c  o  m*/
        raf = new RandomAccessFile(file, "r");
        size = raf.length() > Integer.MAX_VALUE ? Integer.MAX_VALUE : Long.valueOf(raf.length()).intValue();
        System.out.println("file size =" + size);
        buffer = raf.getChannel().map(MapMode.READ_ONLY, 0, size);
        buffer.load();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                closed = true;
                MappedByteBufferUtil.unmap(buffer);
                try {
                    raf.close();
                } catch (IOException e) {
                }
            }
        });
    } catch (IOException e) {
        throw new InitialisationException(e);
    }
}

From source file:de.micromata.genome.logging.spi.ifiles.IndexedReader.java

public void selectLogsImpl(Timestamp start, Timestamp end, Integer loglevel, String category, String msg,
        List<Pair<String, String>> logAttributes, int startRow, int maxRow, List<OrderBy> orderBy,
        boolean masterOnly, LogEntryCallback callback) throws EndOfSearch, IOException {
    int skipRows = startRow;
    int rowsSelected = 0;
    int indexMaxSize = (int) indexChannel.size();
    List<Pair<Integer, Integer>> offsets = indexHeader.getCandiates(start, end, indexByteBuffer, indexMaxSize);
    if (offsets.isEmpty() == true) {
        return;//ww w.  ja  va2 s .  c  o m
    }
    logRandomAccessFile = new RandomAccessFile(logFile, "r");
    //    logChannel = logRandomAccessFile.getChannel();
    //    logByteBuffer = logChannel.map(FileChannel.MapMode.READ_ONLY, 0, logChannel.size());
    if (orderBy != null && orderBy.isEmpty() == false) {

    }
    for (Pair<Integer, Integer> offset : offsets) {
        if (rowsSelected >= maxRow) {
            return;
        }
        if (apply(offset.getFirst(), loglevel, category, msg, logAttributes) == false) {
            continue;
        }
        if (skipRows > 0) {
            --skipRows;
            continue;
        }
        callback.onRow(select(offset.getFirst(), masterOnly));
        ++rowsSelected;
    }
}

From source file:com.android.volley.toolbox.DownloadNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        RandomAccessFile acessfile = null;
        File file = null;/*from  www. ja va 2s . c om*/
        try {
            if (!(request instanceof DownOrUpRequest)) {
                throw new IllegalArgumentException("request object mast be DownOrUpRequest???");
            }
            DownOrUpRequest requestDown = (DownOrUpRequest) request;
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            // Download have no cache
            file = getFile(requestDown);
            acessfile = new RandomAccessFile(file, "rws");

            long length = acessfile.length();
            acessfile.seek(length);
            if (length != 0) {
                headers.put("Range", "bytes=" + length + "-");//
            }
            httpResponse = mHttpStack.performRequest(requestDown, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, requestDown, responseContents, statusLine);

            if (statusCode < 200 || statusCode > 299) {
                acessfile.close();
                throw new IOException();
            }
            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity(), requestDown, acessfile);
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }
            acessfile.close();
            String re = null;
            if (!requestDown.isCanceled() || requestDown.getmMaxLength() == requestDown.getmCurLength()) {
                String path = file.getAbsolutePath();
                String re_name = ((DownOrUpRequest) request).getmDownloadName();
                if (re_name != null) {
                    re = path.substring(0, path.lastIndexOf('/')) + "/" + re_name;
                } else {
                    re = path.substring(0, path.lastIndexOf("."));
                }
                File rename = new File(re);
                boolean result = file.renameTo(rename);
                if (!result) {
                    Log.e(this.getClass().getName(),
                            "?????:"
                                    + rename);
                    throw new IOException(
                            "????????");
                }
                requestDown.setDownloadFile(rename);
            } else {
                re = file.getAbsolutePath();
                statusCode = 209;
            }
            return new NetworkResponse(statusCode, re.getBytes(), responseHeaders, false,
                    SystemClock.elapsedRealtime() - requestStart);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            if (acessfile != null) {
                try {
                    acessfile.close();
                    file.delete();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            throw new NetworkError(networkResponse);
        }
    }
}

From source file:at.tuwien.minimee.util.TopParser.java

/**
 * The process ID is in the last line of the file and looks like follows:
 * monitored_pid= 6738 /*  ww  w  .  j  a  v a 2 s  .c  o  m*/
 * 
 * @param input
 * @return
 * @throws Exception
 */
private Integer findPid() throws Exception {

    Integer pid = new Integer(0);

    // we open the file
    RandomAccessFile f = new RandomAccessFile(file, "r");

    try {

        long size = f.length();

        f.seek(size - 2);

        // we search the file reverse for '='
        byte[] b = new byte[1];
        for (long i = size - 2; i >= 0; i--) {
            f.seek(i);
            f.read(b);
            if (b[0] == '=') {
                break;
            }
        }

        String line = f.readLine().trim();

        pid = new Integer(line);

    } finally {
        // this is important, RandomAccessFile doesn't close the file handle by default!
        // if close isn't called, you'll get very soon 'too many open files'
        f.close();
    }

    return pid;
}

From source file:com.slytechs.capture.file.editor.FileEditorImpl.java

/**
 * @param file/*from   w ww .j  a v  a  2s. c  o m*/
 * @param mode
 *          TODO
 * @param headerReader
 * @param order TODO
 * @param protocolFilter
 *          TODO
 * @param rawBuilder TODO
 * @throws IOException
 */
public FileEditorImpl(final File file, final FileMode mode, final HeaderReader headerReader, ByteOrder order,
        Filter<ProtocolFilterTarget> protocolFilter, RawIteratorBuilder rawBuilder) throws IOException {

    this.file = file;
    this.order = order;
    this.protocolFilter = protocolFilter;
    this.rawBuilder = rawBuilder;
    this.channel = new RandomAccessFile(file, (mode.isContent() || mode.isAppend() ? "rw" : "r")).getChannel();
    this.mode = mode;
    this.headerReader = headerReader;

    final boolean readonly = !mode.isStructure();
    final boolean append = mode.isAppend();

    final PartialLoader loader = new PartialFileLoader(channel, mode, headerReader, file);
    this.edits = new FlexRegion<PartialLoader>(readonly, append, channel.size(), loader);
}