Example usage for java.io RandomAccessFile length

List of usage examples for java.io RandomAccessFile length

Introduction

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

Prototype

public native long length() throws IOException;

Source Link

Document

Returns the length of this file.

Usage

From source file:com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheckTest.java

@Test
public void testWrongSeparatorLength() throws Exception {
    NewlineAtEndOfFileCheck check = new NewlineAtEndOfFileCheck();
    final DefaultConfiguration checkConfig = createCheckConfig(NewlineAtEndOfFileCheck.class);
    check.configure(checkConfig);//www  .java 2s .  c  o  m

    Method method = NewlineAtEndOfFileCheck.class.getDeclaredMethod("endsWithNewline", RandomAccessFile.class);
    method.setAccessible(true);
    RandomAccessFile file = mock(RandomAccessFile.class);
    when(file.length()).thenReturn(2000000L);
    try {
        method.invoke(new NewlineAtEndOfFileCheck(), file);
    } catch (InvocationTargetException ex) {
        assertTrue(ex.getCause() instanceof IOException);
        if (System.getProperty("os.name").toLowerCase(ENGLISH).startsWith("windows")) {
            assertEquals("Unable to read 2 bytes, got 0", ex.getCause().getMessage());
        } else {
            assertEquals("Unable to read 1 bytes, got 0", ex.getCause().getMessage());
        }
    }
}

From source file:org.apache.tajo.storage.http.ExampleHttpServerHandler.java

private void processGet(ChannelHandlerContext context, FullHttpRequest request) {
    try {//from  ww  w  .  j a va2  s  . c  o  m
        File file = getRequestedFile(request.getUri());

        RandomAccessFile raf = new RandomAccessFile(file, "r");
        long fileLength = raf.length();

        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        HttpHeaders.setContentLength(response, fileLength);
        setContentTypeHeader(response, file);

        context.write(response);

        context.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength));

        // Write the end marker.
        ChannelFuture future = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        future.addListener(ChannelFutureListener.CLOSE);

    } catch (IOException | URISyntaxException e) {
        context.writeAndFlush(getBadRequest(e.getMessage()));
    }
}

From source file:com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck.java

/**
 * Checks whether the content provided by the Reader ends with the platform
 * specific line separator.// w w w .  java 2 s .  c o  m
 * @param randomAccessFile The reader for the content to check
 * @return boolean Whether the content ends with a line separator
 * @throws IOException When an IO error occurred while reading from the
 *         provided reader
 */
private boolean endsWithNewline(RandomAccessFile randomAccessFile) throws IOException {
    final int len = lineSeparator.length();
    if (randomAccessFile.length() < len) {
        return false;
    }
    randomAccessFile.seek(randomAccessFile.length() - len);
    final byte[] lastBytes = new byte[len];
    final int readBytes = randomAccessFile.read(lastBytes);
    if (readBytes != len) {
        throw new IOException("Unable to read " + len + " bytes, got " + readBytes);
    }
    return lineSeparator.matches(lastBytes);
}

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

/**
 * get the music info//  w ww. ja v  a  2s  .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;
}

From source file:org.apache.jackrabbit.oak.segment.file.TarReader.java

/**
 * Scans through the tar file, looking for all segment entries.
 *
 * @throws IOException if the tar file could not be read
 *///from   w ww .  j  a v a  2 s  .  c o m
private static void recoverEntries(File file, RandomAccessFile access, LinkedHashMap<UUID, byte[]> entries)
        throws IOException {
    byte[] header = new byte[BLOCK_SIZE];
    while (access.getFilePointer() + BLOCK_SIZE <= access.length()) {
        // read the tar header block
        access.readFully(header);

        // compute the header checksum
        int sum = 0;
        for (int i = 0; i < BLOCK_SIZE; i++) {
            sum += header[i] & 0xff;
        }

        // identify possible zero block
        if (sum == 0 && access.getFilePointer() + 2 * BLOCK_SIZE == access.length()) {
            return; // found the zero blocks at the end of the file
        }

        // replace the actual stored checksum with spaces for comparison
        for (int i = 148; i < 148 + 8; i++) {
            sum -= header[i] & 0xff;
            sum += ' ';
        }

        byte[] checkbytes = String.format("%06o\0 ", sum).getBytes(UTF_8);
        for (int i = 0; i < checkbytes.length; i++) {
            if (checkbytes[i] != header[148 + i]) {
                log.warn("Invalid entry checksum at offset {} in tar file {}, skipping...",
                        access.getFilePointer() - BLOCK_SIZE, file);
            }
        }

        // The header checksum passes, so read the entry name and size
        ByteBuffer buffer = wrap(header);
        String name = readString(buffer, 100);
        buffer.position(124);
        int size = readNumber(buffer, 12);
        if (access.getFilePointer() + size > access.length()) {
            // checksum was correct, so the size field should be accurate
            log.warn("Partial entry {} in tar file {}, ignoring...", name, file);
            return;
        }

        Matcher matcher = NAME_PATTERN.matcher(name);
        if (matcher.matches()) {
            UUID id = UUID.fromString(matcher.group(1));

            String checksum = matcher.group(3);
            if (checksum != null || !entries.containsKey(id)) {
                byte[] data = new byte[size];
                access.readFully(data);

                // skip possible padding to stay at block boundaries
                long position = access.getFilePointer();
                long remainder = position % BLOCK_SIZE;
                if (remainder != 0) {
                    access.seek(position + (BLOCK_SIZE - remainder));
                }

                if (checksum != null) {
                    CRC32 crc = new CRC32();
                    crc.update(data);
                    if (crc.getValue() != Long.parseLong(checksum, 16)) {
                        log.warn("Checksum mismatch in entry {} of tar file {}, skipping...", name, file);
                        continue;
                    }
                }

                entries.put(id, data);
            }
        } else if (!name.equals(file.getName() + ".idx")) {
            log.warn("Unexpected entry {} in tar file {}, skipping...", name, file);
            long position = access.getFilePointer() + size;
            long remainder = position % BLOCK_SIZE;
            if (remainder != 0) {
                position += BLOCK_SIZE - remainder;
            }
            access.seek(position);
        }
    }
}

From source file:net.sf.zekr.common.resource.QuranText.java

/**
 * The private constructor, which loads the whole Quran text from file into memory (<code>quranText</code>
 * ).//from  w w  w .j  a  va2  s .  c  o  m
 * 
 * @param textType can be either UTHMANI_MODE or SIMPLE_MODE
 * @throws IOException
 */
protected QuranText(int textType) throws IOException {
    mode = textType;
    String qFile = ApplicationPath.SIMPLE_QURAN_TEXT_FILE;
    if (textType == UTHMANI_MODE) {
        qFile = ApplicationPath.UTHMANI_QURAN_TEXT_FILE;
    }

    RandomAccessFile raf = new RandomAccessFile(qFile, "r");
    byte[] buf = new byte[(int) raf.length()];
    raf.readFully(buf);
    rawText = new String(buf, config.getProps().getString("quran.text.encoding"));
    refineRawText();
    raf.close();
}

From source file:org.openoverlayrouter.noroot.logActivity.java

public void refresh() {

    StringBuffer contents = new StringBuffer();

    final StringBuffer fixedContents = contents;

    try {/*from www.  j a v  a 2s .c o m*/
        RandomAccessFile logFile = new RandomAccessFile(log_file, "r");
        if (logFile.length() > maxReadBytes) {
            logFile.seek(logFile.length() - maxReadBytes);
        }
        String currentLine = logFile.readLine();
        while (currentLine != null) {

            if (currentLine != null) {
                contents.append(currentLine);
                contents.append('\n');
            }
            currentLine = logFile.readLine();
        }
        try {
            if (logFile != null) {
                logFile.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {

    }

    mHandler.post(new Runnable() {
        public void run() {

            // Put the file contents into the TextView
            TextView log = (TextView) llLayout.findViewById(R.id.logView);
            log.setText(fixedContents);

            // Auto scroll to the bottom
            final ScrollView scroll = (ScrollView) llLayout.findViewById(R.id.scrollView1);
            scroll.post(new Runnable() {
                public void run() {
                    scroll.fullScroll(View.FOCUS_DOWN);
                }
            });
            if (myDialog != null) {
                myDialog.dismiss();
                myDialog = null;
            }
        }
    });
}

From source file:com.liferay.faces.bridge.renderkit.primefaces.internal.PrimeFacesFileItem.java

public byte[] get() {

    byte[] bytes = null;

    try {/*w ww .  jav a  2 s  . co m*/
        File file = new File(uploadedFile.getAbsolutePath());

        if (file.exists()) {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
            bytes = new byte[(int) randomAccessFile.length()];
            randomAccessFile.readFully(bytes);
            randomAccessFile.close();
            file.delete();
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return bytes;
}

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);/*ww w .  java2s  .  c  o m*/
    file.write(chunk, 0, chunk.length);
    length = Math.max(length, file.length());
    return chunk.length;
}

From source file:se.kth.ssvl.tslab.wsn.service.bpf.ActionReceiver.java

@Override
public void bundleReceived(Bundle bundle) {
    Log.i(TAG, "Received bundle! Reading:");
    switch (bundle.payload().location()) {
    case DISK:/* w  w w  .j a v  a  2s  .  co  m*/
        RandomAccessFile f = null;
        try {
            f = new RandomAccessFile(bundle.payload().file(), "r");
            byte[] buffer = new byte[(int) f.length()];
            f.read(buffer);
            Log.i(TAG, new String(buffer));
        } catch (FileNotFoundException e) {
            Log.e(TAG, "Payload should be in file: " + bundle.payload().file().getAbsolutePath()
                    + ". But did not exist!");
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        } finally {
            try {
                f.close();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }
        }
        break;
    case MEMORY:
        try {
            Log.i(TAG, new String(bundle.payload().memory_buf()));
        } catch (BundleLockNotHeldByCurrentThread e) {
            e.printStackTrace();
        }
        break;
    default:
        Log.w(TAG, "The bundle was neither stored in disk nor memory");
    }
}