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:org.apache.cordova.core.FileUtils.java

/**
 * Truncate the file to size/*from  w  w  w . ja  v a  2 s .  c o  m*/
 *
 * @param filename
 * @param size
 * @throws FileNotFoundException, IOException
 * @throws NoModificationAllowedException
 */
private long truncateFile(String filename, long size)
        throws FileNotFoundException, IOException, NoModificationAllowedException {
    if (filename.startsWith("content://")) {
        throw new NoModificationAllowedException("Couldn't truncate file given its content URI");
    }

    filename = FileHelper.getRealPath(filename, cordova);

    RandomAccessFile raf = new RandomAccessFile(filename, "rw");
    try {
        if (raf.length() >= size) {
            FileChannel channel = raf.getChannel();
            channel.truncate(size);
            return size;
        }

        return raf.length();
    } finally {
        raf.close();
    }
}

From source file:caesar.feng.framework.utils.ACache.java

/**
 * ? byte ?//from w  ww  . j a  v  a 2 s . co  m
 * 
 * @param key
 * @return byte ?
 */
public byte[] getAsBinary(String key) {
    RandomAccessFile RAFile = null;
    boolean removeFile = false;
    try {
        File file = mCache.get(key);
        if (!file.exists())
            return null;
        RAFile = new RandomAccessFile(file, "r");
        byte[] byteArray = new byte[(int) RAFile.length()];
        RAFile.read(byteArray);
        if (!Utils.isDue(byteArray)) {
            return Utils.clearDateInfo(byteArray);
        } else {
            removeFile = true;
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (RAFile != null) {
            try {
                RAFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (removeFile)
            remove(key);
    }
}

From source file:com.siblinks.ws.service.impl.CommentServiceImpl.java

/**
 * {@inheritDoc}//from  w  w w .  j  av a 2s .  c  o  m
 */
@Override
@RequestMapping(value = "/getImageComment/{name}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImageComment(@PathVariable(value = "name") final String name) {
    ResponseEntity<byte[]> responseEntity = null;
    RandomAccessFile randomAccessFile = null;
    try {
        if (name != null) {
            String directory = environment.getProperty("directoryImageComment");
            String path = directory + "/" + name + ".png";

            randomAccessFile = new RandomAccessFile(path, "r");
            byte[] r = new byte[(int) randomAccessFile.length()];
            randomAccessFile.readFully(r);
            responseEntity = new ResponseEntity<byte[]>(r, new HttpHeaders(), HttpStatus.OK);
        } else {
            responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT);
        }
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
    } finally {
        try {
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
        } catch (IOException e) {
            // Do nothing
        }
    }
    return responseEntity;

}

From source file:com.siblinks.ws.service.impl.CommentServiceImpl.java

/**
 * This method to get image from path directory Image question
 *
 * @param image//from w w  w  .  j a  v a  2s  . c  o  m
 *            name
 *
 */
@Override
@RequestMapping(value = "/getImageQuestion/{name}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImageQuestion(@PathVariable(value = "name") final String name) {
    RandomAccessFile t = null;
    ResponseEntity<byte[]> responseEntity = null;
    try {
        if (name != null) {
            String directory = environment.getProperty("directoryImageQuestion");

            String path = directory + "/" + name + ".png";

            t = new RandomAccessFile(path, "r");
            byte[] r = new byte[(int) t.length()];
            t.readFully(r);
            responseEntity = new ResponseEntity<byte[]>(r, new HttpHeaders(), HttpStatus.OK);
        } else {
            responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT);
        }
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
    } finally {
        try {
            if (t != null) {
                t.close();
            }
        } catch (IOException e) {
            // do nothing
        }
    }
    return responseEntity;
}

From source file:hotbeans.support.FileSystemHotBeanModuleRepository.java

/**
 * Obtains a file lock on the repository lock file.
 *//*from   w  w  w.  j a v a2s.c o m*/
protected RepositoryFileLock obtainRepositoryFileLock(final boolean shared, final int timeout)
        throws IOException {
    Log logger = this.getLog();

    if (logger.isDebugEnabled())
        logger.debug("Obtaining repository file lock (shared: " + shared + ").");

    RepositoryFileLock repositoryFileLock = null;
    FileLock lock = null;
    final long beginWait = System.currentTimeMillis();

    while (repositoryFileLock == null) {
        try {
            RandomAccessFile lockFile = new RandomAccessFile(
                    new File(moduleRepositoryDirectory, LOCK_FILE_NAME), "rws");
            FileChannel channel = lockFile.getChannel();

            // Attempt to obtain a lock on the file
            lock = channel.tryLock(0L, Long.MAX_VALUE, shared);
            if (!shared && (lockFile.length() == 0)) {
                lockFile.write(new String("LOCK").getBytes());
                lockFile.getFD().sync();
            }
            repositoryFileLock = new RepositoryFileLock(lockFile, lock);
        } catch (IOException ioe) {
            if (logger.isDebugEnabled())
                logger.debug("Error obtaining repository file lock (shared: " + shared + ").", ioe);
            if (timeout < 0)
                throw ioe;
        } catch (OverlappingFileLockException ofle) {
            if (logger.isDebugEnabled())
                logger.debug("Error obtaining repository file lock (shared: " + shared + ").", ofle);
            if (timeout < 0)
                throw ofle;
        }

        if (repositoryFileLock == null) // This statement shouldn't be reaced if timeout is < 0
        {
            if ((System.currentTimeMillis() - beginWait) > timeout) // Wait a maximum of timeout milliseconds on lock
            {
                throw new IOException("Timeout while waiting for file lock on repository lock file!");
            } else {
                // Otherwise - wait a while before trying to obtain a lock again
                try {
                    Thread.sleep(Math.min(250, timeout - (System.currentTimeMillis() - beginWait)));
                } catch (InterruptedException ie) {
                }
            }
        }
    }

    if (logger.isDebugEnabled())
        logger.debug("Repository file lock (shared: " + shared + ") obtained.");

    return repositoryFileLock;
}

From source file:com.guodong.sun.guodong.uitls.CacheUtil.java

/**
 * ? byte ?//  w ww .jav  a 2s. c  o  m
 *
 * @param key
 * @return byte ?
 */
public byte[] getAsBinary(String key) {
    RandomAccessFile raFile = null;
    boolean removeFile = false;
    try {
        File file = mCache.get(key);
        if (!file.exists())
            return null;
        raFile = new RandomAccessFile(file, "r");
        byte[] byteArray = new byte[(int) raFile.length()];
        raFile.read(byteArray);
        if (!Utils.isDue(byteArray)) {
            return Utils.clearDateInfo(byteArray);
        } else {
            removeFile = true;
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (raFile != null) {
            try {
                raFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (removeFile)
            remove(key);
    }
}

From source file:com.android.volley.cache.ACache.java

/**
 * ? byte ?//from  w  w  w .j  a  v a 2 s  . c o  m
 * 
 * @param key
 * @return byte ?
 */
//   public byte[] getAsBinary(String key) {
public BinaryShell getAsBinary(String key) {
    RandomAccessFile RAFile = null;
    //      boolean removeFile = false;
    try {
        File file = mCache.get(key);
        if (!file.exists())
            return null;
        RAFile = new RandomAccessFile(file, "r");
        byte[] byteArray = new byte[(int) RAFile.length()];
        RAFile.read(byteArray);

        BinaryShell shell = new BinaryShell();
        shell.content = Utils.clearDateInfo(byteArray);
        if (!Utils.isDue(byteArray)) {
            shell.outOfDate = false;
        } else {
            shell.outOfDate = true;
        }
        //         if (!Utils.isDue(byteArray)) {
        //            return Utils.clearDateInfo(byteArray);
        //         } else {
        //            removeFile = true;
        //            return null;
        //         }
        return shell;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (RAFile != null) {
            try {
                RAFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //         if (removeFile)
        //            remove(key);
    }
}

From source file:au.org.ala.layers.dao.ObjectDAOImpl.java

@Override
public List<Objects> getObjectsById(String id, int start, int pageSize) {
    logger.info("Getting object info for fid = " + id);
    String limit_offset = " limit " + (pageSize < 0 ? "all" : pageSize) + " offset " + start;
    String sql = "select o.pid as pid, o.id as id, o.name as name, o.desc as description, "
            + "o.fid as fid, f.name as fieldname, o.bbox, o.area_km, "
            + "ST_AsText(ST_Centroid(o.the_geom)) as centroid,"
            + "GeometryType(o.the_geom) as featureType from objects o, fields f "
            + "where o.fid = ? and o.fid = f.id order by o.pid " + limit_offset;
    List<Objects> objects = jdbcTemplate.query(sql,
            ParameterizedBeanPropertyRowMapper.newInstance(Objects.class), id);

    updateObjectWms(objects);/*w ww  .  j a v  a 2  s .c o  m*/

    // get grid classes
    if (objects == null || objects.isEmpty()) {
        objects = new ArrayList<Objects>();
        IntersectionFile f = layerIntersectDao.getConfig().getIntersectionFile(id);
        if (f != null && f.getClasses() != null) {
            //shape position
            int pos = 0;

            for (Entry<Integer, GridClass> c : f.getClasses().entrySet()) {
                File file = new File(f.getFilePath() + File.separator + c.getKey() + ".wkt.index.dat");
                if (f.getType().equals("a") || !file.exists()) { // class pid
                    if (pageSize == -1 || (pos >= start && pos - start < pageSize)) {
                        Objects o = new Objects();
                        o.setPid(f.getLayerPid() + ":" + c.getKey());
                        o.setId(f.getLayerPid() + ":" + c.getKey());
                        o.setName(c.getValue().getName());
                        o.setFid(f.getFieldId());
                        o.setFieldname(f.getFieldName());
                        o.setBbox(c.getValue().getBbox());
                        o.setArea_km(c.getValue().getArea_km());
                        o.setWmsurl(getGridClassWms(f.getLayerName(), c.getValue()));
                        objects.add(o);
                    }
                    pos++;

                    if (pageSize != -1 && pos >= start + pageSize) {
                        break;
                    }
                } else { // polygon pid
                    RandomAccessFile raf = null;
                    try {
                        raf = new RandomAccessFile(file, "r");
                        long itemSize = (4 + 4 + 4 * 4 + 4);
                        long len = raf.length() / itemSize; // group

                        if (pageSize != -1 && pos + len < start) {
                            pos += len;
                        } else {
                            // number,
                            // character
                            // offset,
                            // minx,
                            // miny,
                            // maxx,
                            // maxy,
                            // area
                            // sq
                            // km
                            int i = 0;
                            if (pageSize != -1 && pos < start) {
                                //the first object requested is in this file, seek to the start
                                i = start - pos;
                                pos += i;
                                raf.seek(i * itemSize);
                            }
                            for (; i < len; i++) {
                                int n = raf.readInt();
                                /* int charoffset = */
                                raf.readInt();
                                float minx = raf.readFloat();
                                float miny = raf.readFloat();
                                float maxx = raf.readFloat();
                                float maxy = raf.readFloat();
                                float area = raf.readFloat();

                                if (pageSize == -1 || (pos >= start && pos - start < pageSize)) {
                                    Objects o = new Objects();
                                    o.setPid(f.getLayerPid() + ":" + c.getKey() + ":" + n);
                                    o.setId(f.getLayerPid() + ":" + c.getKey() + ":" + n);
                                    o.setName(c.getValue().getName());
                                    o.setFid(f.getFieldId());
                                    o.setFieldname(f.getFieldName());

                                    o.setBbox("POLYGON((" + minx + " " + miny + "," + minx + " " + maxy + ","
                                            + +maxx + " " + maxy + "," + +maxx + " " + miny + "," + +minx + " "
                                            + miny + "))");
                                    o.setArea_km(1.0 * area);

                                    o.setWmsurl(getGridPolygonWms(f.getLayerName(), n));

                                    objects.add(o);
                                }

                                pos++;

                                if (pageSize != -1 && pos >= start + pageSize) {
                                    break;
                                }
                            }
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (raf != null) {
                            try {
                                raf.close();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }

                    if (pageSize != -1 && pos >= start + pageSize) {
                        break;
                    }
                }
            }
        }
    }
    return objects;
}

From source file:net.sf.ehcache.DiskStoreTest.java

/**
 * Tests how data is written to a random access file.
 * <p/>//from w  w  w  .  jav a2  s.  co  m
 * It makes sure that bytes are immediately written to disk after a write.
 */
public void testWriteToFile() throws IOException {
    // Create and set up file
    String dataFileName = "fileTest";
    RandomAccessFile file = getRandomAccessFile(dataFileName);

    //write data to the file
    byte[] buffer = new byte[1024];
    for (int i = 0; i < 100; i++) {
        file.write(buffer);
    }

    assertEquals(1024 * 100, file.length());

}

From source file:com.limegroup.gnutella.metadata.MP3DataEditor.java

/**
 * Actually writes the ID3 tags out to the ID3V1 section of mp3 file.
 *///w  w  w . j  av a  2s . c o m
private int writeID3V1DataToDisk(RandomAccessFile file) {
    byte[] buffer = new byte[30];//max buffer length...drop/pickup vehicle

    //see if there are ID3 Tags in the file
    String tag = "";
    try {
        file.readFully(buffer, 0, 3);
        tag = new String(buffer, 0, 3);
    } catch (EOFException e) {
        return LimeXMLReplyCollection.RW_ERROR;
    } catch (IOException e) {
        return LimeXMLReplyCollection.RW_ERROR;
    }
    //We are sure this is an MP3 file.Otherwise this method would never
    //be called.
    if (!tag.equals("TAG")) {
        //Write the TAG
        try {
            byte[] tagBytes = "TAG".getBytes();//has to be len 3
            file.seek(file.length() - 128);//reset the file-pointer
            file.write(tagBytes, 0, 3);//write these three bytes into the File
        } catch (IOException ioe) {
            return LimeXMLReplyCollection.BAD_ID3;
        }
    }
    LOG.debug("about to start writing to file");
    boolean b;
    b = toFile(title_, 30, file, buffer);
    if (!b)
        return LimeXMLReplyCollection.FAILED_TITLE;
    b = toFile(artist_, 30, file, buffer);
    if (!b)
        return LimeXMLReplyCollection.FAILED_ARTIST;
    b = toFile(album_, 30, file, buffer);
    if (!b)
        return LimeXMLReplyCollection.FAILED_ALBUM;
    b = toFile(year_, 4, file, buffer);
    if (!b)
        return LimeXMLReplyCollection.FAILED_YEAR;
    //comment and track (a little bit tricky)
    b = toFile(comment_, 28, file, buffer);//28 bytes for comment
    if (!b)
        return LimeXMLReplyCollection.FAILED_COMMENT;

    byte trackByte = (byte) -1;//initialize
    try {
        if (track_ == null || track_.equals(""))
            trackByte = (byte) 0;
        else
            trackByte = Byte.parseByte(track_);
    } catch (NumberFormatException nfe) {
        return LimeXMLReplyCollection.FAILED_TRACK;
    }

    try {
        file.write(0);//separator b/w comment and track(track is optional)
        file.write(trackByte);
    } catch (IOException e) {
        return LimeXMLReplyCollection.FAILED_TRACK;
    }

    //genre
    byte genreByte = getGenreByte();
    try {
        file.write(genreByte);
    } catch (IOException e) {
        return LimeXMLReplyCollection.FAILED_GENRE;
    }
    //come this far means we are OK.
    return LimeXMLReplyCollection.NORMAL;

}