List of usage examples for java.io RandomAccessFile RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
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 2s .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.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 {//from www .java2s . 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.excuseme.rocketleaguelivestats.scanner.tailer.Tailer.java
/** * Follows changes in the file, calling the TailerListener's handle method for each new line. */// w w w .ja v a 2s.co m public void run() { RandomAccessFile reader = null; try { long last = 0; // The last time the file was checked for changes long position = 0; // position within the file // Open the file while (run && reader == null) { try { reader = new RandomAccessFile(file, RAF_MODE); } catch (FileNotFoundException e) { listener.fileNotFound(); } if (reader == null) { try { Thread.sleep(delayMillis); } catch (InterruptedException e) { } } else { // The current position in the file position = end ? file.length() : 0; last = System.currentTimeMillis(); reader.seek(position); } } while (run) { boolean newer = FileUtils.isFileNewer(file, last); // IO-279, must be done first // Check the file length to see if it was rotated long length = file.length(); if (length < position) { // File was rotated listener.fileRotated(); // Reopen the reader after rotation try { // Ensure that the old file is closed iff we re-open it successfully RandomAccessFile save = reader; reader = new RandomAccessFile(file, RAF_MODE); position = 0; // close old file explicitly rather than relying on GC picking up previous RAF IOUtils.closeQuietly(save); } catch (FileNotFoundException e) { // in this case we continue to use the previous reader and position values listener.fileNotFound(); } continue; } else { // File was not rotated // See if the file needs to be read again if (length > position) { // The file has more content than it did last time position = readLines(reader); last = System.currentTimeMillis(); } else if (newer) { /* * This can happen if the file is truncated or overwritten with the exact same length of * information. In cases like this, the file position needs to be reset */ position = 0; reader.seek(position); // cannot be null here // Now we can read new lines position = readLines(reader); last = System.currentTimeMillis(); } } if (reOpen) { IOUtils.closeQuietly(reader); } try { Thread.sleep(delayMillis); } catch (InterruptedException e) { } if (run && reOpen) { reader = new RandomAccessFile(file, RAF_MODE); reader.seek(position); } } } catch (Exception e) { listener.handle(e); } finally { IOUtils.closeQuietly(reader); } }
From source file:com.aliyun.android.oss.task.GetObjectTask.java
/** * ???//from w w w.j ava 2 s. c o m * @param {@link OSSObject}??? * @return {@link OSSClientUtil} * @throws OSSException */ public int getResult(OSSObject object) throws OSSException { int result = CloudUtil.CLOUDCLIENT_RESULT_OK; HttpResponse response = null; RandomAccessFile randomAccessFile = null; InputStream inputStream = null; object = new OSSObject(this.bucketName, this.objectKey); try { mLogMission.i("getResult", "before network request", missionObject); response = this.execute(); mLogMission.i("getResult", "network response", missionObject); Header rangeHeader = response.getFirstHeader("Content-Range"); if (rangeHeader != null) { String range = rangeHeader.getValue(); mLogMission.i("getResult", "range:" + range.toString(), missionObject); } object.setObjectMetaData(OSSHttpTool.getObjectMetadataFromResponse(response)); if (response.getEntity() != null) { mLogMission.i("getResult", "the content length get from server:" + response.getEntity().getContentLength(), missionObject); if (missionObject.getFileLength() <= 0L) { missionObject.setFileLength(response.getEntity().getContentLength()); mLogMission.i("getResult", "get content length and set file length. fileLength:" + missionObject.getFileLength(), missionObject); } missionObject.setPaused(false); inputStream = response.getEntity().getContent(); if (listener != null) { listener.setTotalSize(missionObject.getFileLength()); } } result = mDatabaseAccessManager.updateDownloadFile(missionObject); if (result != CloudUtil.CLOUDCLIENT_RESULT_OK) { return result; } randomAccessFile = new RandomAccessFile(filePath, "rwd"); long offset = 0; if (range != null) { offset = range.getStart(); mLogMission.i("getResult", "set offset before write file, offset:" + offset, missionObject); } randomAccessFile.seek(offset); mLogMission.i("getResult", "before write to local, file offset:" + offset, missionObject); byte[] buffer = new byte[1024 * 4]; long readTotal = offset; int readLength = 0; while (true) { if (readTotal == missionObject.getFileLength()) { missionObject.setFinished(true); result = CloudUtil.CLOUDCLIENT_RESULT_OK; mLogMission.i("getResult", "readTotal == missionObject's fileLength, readTotal:" + readTotal, missionObject); break; } if (listener != null && listener.isCancel()) { missionObject.setPaused(true); result = CloudUtil.CLOUD_FILE_MISSION_CANCEL; mLogMission.i("getResult", "cancel download missionObject", missionObject); break; } readLength = inputStream.read(buffer); mLogMission.i("getResult", "read buffer length:" + readLength, missionObject); if (readLength == -1) { missionObject.setFinished(true); result = CloudUtil.CLOUDCLIENT_RESULT_OK; mLogMission.i("getResult", "buffer read finish, readLength:" + readLength, missionObject); break; } mLogMission.i("getResult", "write to local, length:" + readLength, missionObject); randomAccessFile.write(buffer, 0, readLength); readTotal += readLength; mLogMission.i("getResult", "readTotal:" + readTotal, missionObject); missionObject.setTransferredLength(readTotal); missionObject.setLastTime(System.currentTimeMillis()); // result = mDatabaseAccessManager.updateDownloadFile(missionObject); // if (result != CloudUtil.CLOUDCLIENT_RESULT_OK) { // break; // } if (listener != null) { listener.transferred(readTotal); } } } catch (OSSException osse) { throw osse; } catch (ParseException pe) { OSSException ossException = new OSSException(pe); ossException.setErrorCode(OSSErrorCode.PARSE_METADATA_ERROR); throw ossException; } catch (IOException ioe) { OSSException ossException = new OSSException(ioe); ossException.setErrorCode(OSSErrorCode.GET_ENTITY_CONTENT_ERROR); throw ossException; } finally { mDatabaseAccessManager.updateDownloadFile(missionObject); mLogMission.i("getResult", "finally, update db", missionObject); this.releaseHttpClient(); if (randomAccessFile != null) { try { inputStream.close(); randomAccessFile.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }
From source file:FileBaseDataMap.java
/** * put Method.<br>/*w ww . j a v a2 s. com*/ * * @param key * @param value * @param hashCode This is a key value hash code */ public void put(String key, String value, int hashCode) { try { File file = dataFileList[hashCode % numberOfDataFiles]; StringBuffer buf = new StringBuffer(this.fillCharacter(key, keyDataLength)); buf.append(this.fillCharacter(value, oneDataLength)); CacheContainer accessor = (CacheContainer) innerCache.get(file.getAbsolutePath()); RandomAccessFile raf = null; BufferedWriter wr = null; if (accessor == null || accessor.isClosed == true) { raf = new RandomAccessFile(file, "rwd"); wr = new BufferedWriter(new FileWriter(file, true)); accessor = new CacheContainer(); accessor.raf = raf; accessor.wr = wr; accessor.file = file; innerCache.put(file.getAbsolutePath(), accessor); } else { raf = accessor.raf; wr = accessor.wr; } // KeyData Write File for (int tryIdx = 0; tryIdx < 2; tryIdx++) { try { // Key?? long dataLineNo = this.getLinePoint(key, raf); if (dataLineNo == -1) { wr.write(buf.toString()); wr.flush(); // The size of an increment this.totalSize.getAndIncrement(); } else { // ?????1 boolean increMentFlg = false; if (this.get(key, hashCode) == null) increMentFlg = true; raf.seek(dataLineNo * (lineDataSize)); raf.write(buf.toString().getBytes(), 0, lineDataSize); if (increMentFlg) this.totalSize.getAndIncrement(); } break; } catch (IOException ie) { // IOException???1???? if (tryIdx == 1) throw ie; try { if (raf != null) raf.close(); if (wr != null) wr.close(); raf = new RandomAccessFile(file, "rwd"); wr = new BufferedWriter(new FileWriter(file, true)); accessor = new CacheContainer(); accessor.raf = raf; accessor.wr = wr; accessor.file = file; innerCache.put(file.getAbsolutePath(), accessor); } catch (Exception e) { throw e; } } } } catch (Exception e2) { e2.printStackTrace(); } }
From source file:com.roamtouch.menuserver.utils.FileUtils.java
private void removeLastCharacter(File fileName) { RandomAccessFile f;/* w w w . j a va 2 s . c o m*/ long length; try { f = new RandomAccessFile(fileName, "rw"); length = f.length(); long l; if (length > 0) l = length - 1; else l = length; f.setLength(l); f.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.amazonaws.eclipse.core.regions.RegionUtils.java
/** * Set the length of the file given to 0 bytes. *//* ww w.j a v a2s . co m*/ private static void truncateFile(File file) throws FileNotFoundException, IOException { if (file.exists()) { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.getChannel().truncate(0); raf.close(); } }
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//from w w w.j av a2 s.co 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:acromusashi.kafka.log.producer.WinApacheLogProducer.java
/** * ????// w w w .j a v a 2 s . c o m * * @param file ? * @return ????byte? * @throws IOException */ private byte[] getTail(File file) throws IOException { byte[] tail = new byte[0]; try (RandomAccessFile random = new RandomAccessFile(file, "r")) { if (this.tailPos < random.length()) { random.seek(this.tailPos); tail = readToEnd(random); } this.tailPos = random.length(); } return tail; }