Example usage for java.io RandomAccessFile seek

List of usage examples for java.io RandomAccessFile seek

Introduction

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

Prototype

public void seek(long pos) throws IOException 

Source Link

Document

Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

Usage

From source file:org.red5.io.flv.FLVReader.java

public static long getDuration(File flvFile) {
    RandomAccessFile flv = null;
    try {/*from   w w w  .j  a  va2 s  .co  m*/
        flv = new RandomAccessFile(flvFile, "r");
        long flvLength = flv.length();
        if (flvLength < 13) {
            return 0;
        }
        flv.seek(flvLength - 4);
        byte[] buf = new byte[4];
        flv.read(buf);
        long lastTagSize = 0;
        for (int i = 0; i < 4; i++) {
            lastTagSize += (buf[i] & 0x0ff) << ((3 - i) * 8);
        }
        if (lastTagSize == 0) {
            return 0;
        }
        flv.seek(flvLength - lastTagSize);
        flv.read(buf);
        long duration = 0;
        for (int i = 0; i < 3; i++) {
            duration += (buf[i] & 0x0ff) << ((2 - i) * 8);
        }
        duration += (buf[3] & 0x0ff) << 24; // extension byte
        return duration;
    } catch (IOException e) {
        return 0;
    } finally {
        try {
            if (flv != null) {
                flv.close();
            }
        } catch (IOException e) {
        }
        flv = null;
    }
}

From source file:org.apache.hadoop.hdfs.TestRaidDfs.java

public static void corruptBlock(Path file, Block blockNum, int numDataNodes, boolean delete,
        MiniDFSCluster cluster) throws IOException {
    long id = blockNum.getBlockId();

    // Now deliberately remove/truncate data blocks from the block.
    int numDeleted = 0;
    int numCorrupted = 0;
    for (int i = 0; i < numDataNodes; i++) {
        File[] dirs = getDataNodeDirs(i, cluster);

        for (int j = 0; j < dirs.length; j++) {
            File[] blocks = dirs[j].listFiles();
            assertTrue("Blocks do not exist in data-dir", (blocks != null) && (blocks.length >= 0));
            for (int idx = 0; idx < blocks.length; idx++) {
                LOG.info("block file: " + blocks[idx]);
                if (blocks[idx].getName().startsWith("blk_" + id) && !blocks[idx].getName().endsWith(".meta")) {
                    if (delete) {
                        blocks[idx].delete();
                        LOG.info("Deleted block " + blocks[idx]);
                        numDeleted++;/*from w  w  w  .  java  2 s.  co m*/
                    } else {
                        // Corrupt
                        File f = blocks[idx];
                        long seekPos = f.length() / 2;
                        RandomAccessFile raf = new RandomAccessFile(f, "rw");
                        raf.seek(seekPos);
                        int data = raf.readInt();
                        raf.seek(seekPos);
                        raf.writeInt(data + 1);
                        LOG.info("Corrupted block " + blocks[idx]);
                        numCorrupted++;
                    }
                }
            }
        }
    }
    assertTrue("Nothing corrupted or deleted", (numCorrupted + numDeleted) > 0);
}

From source file:com.github.nlloyd.hornofmongo.MongoScope.java

public static Object fuzzFile(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    if (args.length != 2)
        Context.throwAsScriptRuntimeEx(new MongoScriptException("fuzzFile takes 2 arguments"));
    File fileToFuzz;/*from  w w  w .  j a va  2  s . c  om*/
    try {
        fileToFuzz = resolveFilePath((MongoScope) thisObj, Context.toString(args[0])).getCanonicalFile();
    } catch (IOException e) {
        Context.throwAsScriptRuntimeEx(new MongoScriptException(e));
        return null;
    }
    RandomAccessFile fuzzFile = null;
    try {
        fuzzFile = new RandomAccessFile(fileToFuzz, "rw");
        long fuzzPosition = Double.valueOf(Context.toNumber(args[1])).longValue();
        fuzzFile.seek(fuzzPosition);
        int byteToFuzz = fuzzFile.readByte();
        byteToFuzz = ~byteToFuzz;
        fuzzFile.seek(fuzzPosition);
        fuzzFile.write(byteToFuzz);
        fuzzFile.close();
    } catch (FileNotFoundException e) {
        Context.throwAsScriptRuntimeEx(e);
    } catch (IOException e) {
        Context.throwAsScriptRuntimeEx(e);
    } finally {
        if (fuzzFile != null) {
            try {
                fuzzFile.close();
            } catch (IOException e) {
            }
        }
    }

    return Undefined.instance;
}

From source file:net.naijatek.myalumni.util.utilities.FileUtil.java

public static String[] getLastLines(final File file, final int linesToReturn, final String logType)
        throws IOException, FileNotFoundException {

    final int AVERAGE_CHARS_PER_LINE = 250;
    final int BYTES_PER_CHAR = 2;

    RandomAccessFile randomAccessFile = null;
    StringBuffer buffer = new StringBuffer(linesToReturn * AVERAGE_CHARS_PER_LINE);
    int lineTotal = 0;
    try {/* ww w.  j av  a2s.  c  o  m*/
        randomAccessFile = new RandomAccessFile(file, "r");
        long byteTotal = randomAccessFile.length();
        long byteEstimateToRead = linesToReturn * AVERAGE_CHARS_PER_LINE * BYTES_PER_CHAR;

        long offset = byteTotal - byteEstimateToRead;
        if (offset < 0) {
            offset = 0;
        }

        randomAccessFile.seek(offset);
        //log.debug("SKIP IS ::" + offset);

        String line = null;
        String lineUTF8 = null;
        while ((line = randomAccessFile.readLine()) != null) {
            lineUTF8 = new String(line.getBytes("ISO8859_1"), "UTF-8");
            lineTotal++;
            buffer.append(lineUTF8).append("\n");
        }
    } finally {
        if (randomAccessFile != null) {
            try {
                randomAccessFile.close();
            } catch (IOException ex) {
            }
        }
    }

    //String[] resultLines = new String[linesToReturn];
    ArrayList<String> resultLines = new ArrayList<String>();
    BufferedReader in = null;
    try {
        in = new BufferedReader(new StringReader(buffer.toString()));

        int start = lineTotal /* + 2 */ - linesToReturn; // Ex : 55 - 10 = 45 ~ offset
        if (start < 0) {
            start = 0; // not start line
        }
        for (int i = 0; i < start; i++) {
            in.readLine(); // loop until the offset. Ex: loop 0, 1 ~~ 2 lines
        }

        int i = 0;
        String line = null;
        while ((line = in.readLine()) != null) {
            if (logType.equalsIgnoreCase("ALL")) {
                //resultLines[i] = line;
                resultLines.add(line);
                i++;
            } else if (line.indexOf(logType) > -1) {
                //resultLines[i] = line;
                resultLines.add(line);
                i++;
            }
        }
    } catch (IOException ie) {
        logger.error("Error" + ie);
        throw ie;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
            }
        }
    }

    String[] resultLines1 = new String[resultLines.size()];
    String tmp = new String();
    for (int i = 0; i < resultLines.size(); i++) {
        tmp = (String) resultLines.get(i);
        resultLines1[i] = tmp;
    }

    return resultLines1;
}

From source file:com.liferay.lms.servlet.SCORMFileServerServlet.java

/**
 * Copy the given byte range of the given input to the given output.
 * @param input The input to copy the given range to the given output for.
 * @param output The output to copy the given range from the given input for.
 * @param start Start of the byte range.
 * @param length Length of the byte range.
 * @throws IOException If something fails at I/O level.
 *///from  w  w w .j  a v  a 2  s . c  o  m
private static void copy(RandomAccessFile input, OutputStream output, long start, long length)
        throws IOException {
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    int read;

    if (input.length() == length) {
        // Write full range.
        while ((read = input.read(buffer)) > 0) {
            output.write(buffer, 0, read);
        }
    } else {
        // Write partial range.
        input.seek(start);
        long toRead = length;

        while ((read = input.read(buffer)) > 0) {
            if ((toRead -= read) > 0) {
                output.write(buffer, 0, read);
            } else {
                output.write(buffer, 0, (int) toRead + read);
                break;
            }
        }
    }
}

From source file:azkaban.common.utils.Utils.java

/**
 * Read in content of a file and get the last *lineCount* lines. It is
 * equivalent to *tail* command/* www  .  ja va  2  s. c  o m*/
 * 
 * @param filename
 * @param lineCount
 * @param chunkSize
 * @return
 */
public static Vector<String> tail(String filename, int lineCount, int chunkSize) {
    try {
        // read in content of the file
        RandomAccessFile file = new RandomAccessFile(filename, "r");
        // destination vector
        Vector<String> lastNLines = new Vector<String>();
        // current position
        long currPos = file.length() - 1;
        long startPos;
        byte[] byteArray = new byte[chunkSize];

        // read in content of the file in reverse order
        while (true) {
            // read in from *fromPos*
            startPos = currPos - chunkSize;

            if (startPos <= 0) { // toward the beginning of the file
                file.seek(0);
                file.read(byteArray, 0, (int) currPos); // only read in
                                                        // curPos bytes
                parseLinesFromLast(byteArray, 0, (int) currPos, lineCount, lastNLines);
                break;
            } else {
                file.seek(startPos);
                if (byteArray == null)
                    byteArray = new byte[chunkSize];
                file.readFully(byteArray);
                if (parseLinesFromLast(byteArray, lineCount, lastNLines)) {
                    break; // we got the last *lineCount* lines
                }

                // move the current position
                currPos = startPos; // + lastLine.getBytes().length;
            }
        }

        // there might be lineCount + 1 lines and the first line (now it is the last line)
        // might not be complete
        for (int index = lineCount; index < lastNLines.size(); index++)
            lastNLines.removeElementAt(index);

        // reverse the order of elements in lastNLines
        Collections.reverse(lastNLines);
        return lastNLines;
    } catch (Exception e) {
        return null;
    }

}

From source file:org.jcodec.movtool.Undo.java

private void undo(String fineName) throws IOException {
    List<Atom> versions = list(fineName);
    if (versions.size() < 2) {
        System.err.println("Nowhere to rollback.");
        return;/*  w w  w.  j a v a2s.  c o m*/
    }
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(new File(fineName), "rw");
        raf.seek(versions.get(versions.size() - 2).getOffset() + 4);
        raf.write(new byte[] { 'm', 'o', 'o', 'v' });
        raf.seek(versions.get(versions.size() - 1).getOffset() + 4);
        raf.write(new byte[] { 'f', 'r', 'e', 'e' });
    } finally {
        raf.close();
    }
}

From source file:ch.cyberduck.core.io.FileBuffer.java

@Override
public synchronized int write(final byte[] chunk, final Long offset) throws IOException {
    final RandomAccessFile file = random();
    file.seek(offset);
    file.write(chunk, 0, chunk.length);/* ww w.  jav  a  2 s. co  m*/
    length = Math.max(length, file.length());
    return chunk.length;
}

From source file:ch.cyberduck.core.io.FileBuffer.java

@Override
public synchronized int read(final byte[] chunk, final Long offset) throws IOException {
    final RandomAccessFile file = random();
    if (offset < file.length()) {
        file.seek(offset);
        if (chunk.length + offset > file.length()) {
            return file.read(chunk, 0, (int) (file.length() - offset));
        } else {//  ww w.  j  av a2 s.  c o m
            return file.read(chunk, 0, chunk.length);
        }
    } else {
        final NullInputStream nullStream = new NullInputStream(length);
        if (nullStream.available() > 0) {
            nullStream.skip(offset);
            return nullStream.read(chunk, 0, chunk.length);
        } else {
            return IOUtils.EOF;
        }
    }
}

From source file:com.tcl.lzhang1.mymusic.MusicUtil.java

/**
 * get the music info//from w  w w . j  a v  a2s  . c  o m
 * 
 * @param musicFile
 * @return
 */
public static SongModel getMusicInfo(File musicFile) {
    SongModel model = new SongModel();
    // retrun null if music file is null or is or directory
    if (musicFile == null || !musicFile.isFile()) {
        return null;
    }

    byte[] buf = new byte[128];
    try {
        Log.d(LOG_TAG, "process music file{" + musicFile.getAbsolutePath() + "}");
        // tag_v1
        RandomAccessFile music = new RandomAccessFile(musicFile, "r");

        music.seek(music.length() - 128);
        music.read(buf);// read tag to buffer
        // tag_v2
        byte[] header = new byte[10];
        music.seek(0);
        music.read(header, 0, 10);
        // if ("ID3".equalsIgnoreCase(new String(header, 0, 3))) {
        // int ID3V2_frame_size = (int) (header[6] & 0x7F) * 0x200000
        // | (int) (header[7] & 0x7F) * 0x400
        // | (int) (header[8] & 0x7F) * 0x80
        // | (int) (header[9] & 0x7F);
        // byte[] FrameHeader = new byte[4];
        // music.seek(ID3V2_frame_size + 10);
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, ID3V2_frame_size, musicFile);
        // } else {
        // byte[] FrameHeader = new byte[4];
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, 0, musicFile);
        // }

        music.close();// close file
        // check length
        // if (buf.length != 128) {
        // throw new
        // ErrorMusicLength(String.format("error music info length, length is:%i",
        // buf.length));
        // }
        //
        // if (!"TAG".equalsIgnoreCase(new String(buf, 0, 3))) {
        // throw new UnknownTagException("unknown tag exception");
        // }
        String songName = null;
        // try {
        // songName = new String(buf, 3, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // e.printStackTrace();
        // songName = new String(buf, 3, 30).trim();
        // }
        String singerName = "";
        // try {
        // singerName = new String(buf, 33, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // singerName = new String(buf, 33, 30).trim();
        // }
        String ablum = "";
        // try {
        // ablum = new String(buf, 63, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // ablum = new String(buf, 63, 30).trim();
        // }
        String year = "";
        // try {
        // year = new String(buf, 93, 4, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // year = new String(buf, 93, 4).trim();
        // // TODO: handle exception
        // }

        String reamrk = "";
        ContentResolver contentResolver = sContext.getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, "_data=?",
                new String[] { musicFile.getAbsolutePath() }, null);
        cursor.moveToFirst();
        if (cursor != null && cursor.getCount() != 0) {
            try {
                if (TextUtils.isEmpty(songName)) {
                    songName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE));
                    singerName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST));
                    ablum = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM));
                    year = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.YEAR));
                }

                long secs = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION));
                model.setTime(secs);
                secs /= 1000;
                model.setHours((int) secs / 3600);
                model.setMinutes(((int) secs % 3600) / 60);
                model.setSeconds(((int) secs % 3600) % 60);
                cursor.close();
            } catch (CursorIndexOutOfBoundsException e) {
                // TODO: handle exception
                if (null != cursor) {
                    cursor.close();
                    cursor = null;
                }
                Log.d(LOG_TAG, "CursorIndexOutOfBoundsException:" + e.getMessage());
                try {
                    songName = new String(buf, 3, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e0) {
                    // TODO: handle exception
                    e.printStackTrace();
                    songName = new String(buf, 3, 30).trim();
                }
                try {
                    singerName = new String(buf, 33, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e1) {
                    // TODO: handle exception
                    singerName = new String(buf, 33, 30).trim();
                }
                try {
                    ablum = new String(buf, 63, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e2) {
                    // TODO: handle exception
                    ablum = new String(buf, 63, 30).trim();
                }
                try {
                    year = new String(buf, 93, 4, "gbk").trim();
                } catch (UnsupportedEncodingException e3) {
                    year = new String(buf, 93, 4).trim();
                    // TODO: handle exception
                }

                try {
                    reamrk = new String(buf, 97, 28, "gbk").trim();
                } catch (UnsupportedEncodingException e4) {
                    // TODO: handle exception
                    reamrk = new String(buf, 97, 28).trim();
                }

            }
        }

        //

        // get the time len

        model.setSongName(songName);
        model.setSingerName(singerName);
        model.setAblumName(ablum);
        model.setFile(musicFile.getAbsolutePath());
        model.setRemark("");
        Log.d(LOG_TAG, String.format("scaned music file[%s],album name[%s],song name[%s],singer name[%s]",
                model.getFile(), model.getAblumName(), model.getSingerName(), model.getSingerName()));

        mSongs.add(model);

        return model;
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return model;
}