List of usage examples for java.io RandomAccessFile length
public native long length() throws IOException;
From source file:com.siblinks.ws.service.impl.ArticleServiceImpl.java
/** * {@inheritDoc}/*from ww w .j ava2 s .c om*/ * */ @SuppressWarnings("resource") @Override @RequestMapping(value = "/getImageArticle/{arId}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) public ResponseEntity<byte[]> getImageArticle(@PathVariable(value = "arId") final String arId) throws IOException { RandomAccessFile t = null; Object[] queryParams = { arId }; String path = null; ResponseEntity<byte[]> responseEntity = null; try { List<Object> readObject = dao.readObjects(SibConstants.SqlMapper.SQL_GET_IMAGE_ARTICLE, queryParams); if (((Map) readObject.get(0)).get(Parameters.IMAGE) != null) { path = ((Map) readObject.get(0)).get(Parameters.IMAGE).toString(); // System.out.print(Paths.get("").toAbsolutePath()+path); path = Paths.get("").toAbsolutePath() + path; byte[] r = null; try { t = new RandomAccessFile(path, "r"); r = new byte[(int) t.length()]; t.readFully(r); } catch (FileNotFoundException e) { e.printStackTrace(); } final HttpHeaders headers = new HttpHeaders(); responseEntity = new ResponseEntity<byte[]>(r, headers, HttpStatus.OK); } else { responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT); } } catch (Exception e) { e.printStackTrace(); responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT); } finally { if (t != null) { t.close(); } } return responseEntity; }
From source file:gate.util.reporting.PRTimeReporter.java
/** * Reads the given file upside down.//from ww w . j a v a2s . com * * @param fileToBeRead * An object of type File representing the file to be read. * @param chunkSize * An integer specifying the size of the chunks in which file will be * read. * @return A long value pointing to the start position of the given file * chunk. * @throws BenchmarkReportInputFileFormatException */ private long tail(File fileToBeRead, int chunkSize) throws BenchmarkReportInputFileFormatException { RandomAccessFile raf = null; try { raf = new RandomAccessFile(fileToBeRead, "r"); Vector<String> lastNlines = new Vector<String>(); int delta = 0; long curPos = raf.length() - 1; long fromPos; byte[] bytearray; while (true) { fromPos = curPos - chunkSize; if (fromPos <= 0) { raf.seek(0); bytearray = new byte[(int) curPos]; raf.readFully(bytearray); if (parseLinesFromLast(bytearray, lastNlines)) { if (fromPos < 0) fromPos = 0; } break; } else { raf.seek(fromPos); bytearray = new byte[chunkSize]; raf.readFully(bytearray); if (parseLinesFromLast(bytearray, lastNlines)) { break; } delta = (lastNlines.get(lastNlines.size() - 1)).length(); lastNlines.remove(lastNlines.size() - 1); curPos = fromPos + delta; } } if (fromPos < 0) throw new BenchmarkReportInputFileFormatException( getBenchmarkFile().getAbsolutePath() + " does not contain a marker named " + getLogicalStart() + " indicating logical start of a run."); return fromPos; } catch (IOException e) { e.printStackTrace(); return -1; } finally { IOUtils.closeQuietly(raf); } }
From source file:org.eclipse.ice.item.utilities.moose.MOOSEFileHandler.java
/** * This operations loads a MOOSE GetPot file at the specified path and * returns a fully-configured set of ICE TreeComposites. * /*from ww w.ja v a2 s. c o m*/ * @param filePath * The file path from which the MOOSE blocks written in GetPot * should be read. If the path is null or empty, the operation * returns without doing any work. * @return The MOOSE input file specification as read from the GetPot input * and stored in TreeComposites. Each TreeComposite contains both * parameters and exemplar children. Any parameters in a * TreeComposite are contained in a DataComponent. The id of the * data component is 1. */ public ArrayList<TreeComposite> loadFromGetPot(String filePath) { // Local Declarations ArrayList<TreeComposite> trees = new ArrayList<TreeComposite>(); byte[] fileByteArray = null; String mooseFileString = null, potLine = null; // Quit if the path is boned if (filePath == null || filePath.isEmpty()) { return null; } // Post some debug info if (debugFlag) { logger.info("MOOSEFileHandler Message: " + "Attempting to loading GetPot file " + filePath); } // Load the GetPot file try { RandomAccessFile mooseFile = new RandomAccessFile(filePath, "r"); // Put it into a byte array fileByteArray = new byte[(int) mooseFile.length()]; mooseFile.read(fileByteArray); // And then a string mooseFileString = new String(fileByteArray); // Close the file mooseFile.close(); // Post some more debug info if (debugFlag) { logger.info("MOOSEFileHandler Message: File loaded."); } } catch (IOException e) { // Complain if the file is not found System.err.println("MOOSEFileHandler Message: " + "Unable to load GetPot file!"); logger.error(getClass().getName() + " Exception!", e); } // Check the string before proceeding if (mooseFileString != null && !mooseFileString.isEmpty()) { // Create an array list from the string ArrayList<String> potLines = new ArrayList<String>(Arrays.asList(mooseFileString.split("\n"))); // Remove (non-parameter) commented lines and white space String trimmedPotLine = ""; for (int i = 0; i < potLines.size(); i++) { trimmedPotLine = potLines.get(i).trim(); if (trimmedPotLine.startsWith("#") && !trimmedPotLine.contains("=") && !trimmedPotLine.contains("[") && !trimmedPotLine.contains("]")) { // Lines that start with "#" but have no "=" are comments // that aren't parameters and should be removed potLines.remove(i); // Update "i" so that we read correctly --i; } else if (potLines.get(i).isEmpty()) { // Remove empty lines potLines.remove(i); // Update "i" so that we read correctly --i; } else { // This is a rare scenario to check for, but it's possible // (and has happened at least once) where a line is just a // comment (starts with "#") AND includes a "=" in the text // of the comment if (trimmedPotLine.startsWith("#") && trimmedPotLine.contains("=")) { String[] splitTrimmedPotLine = trimmedPotLine.split("\\s+"); if (splitTrimmedPotLine.length > 4) { // Skip this line, it's a comment that's been // mistaken as a parameter potLines.remove(i); --i; continue; } } // Otherwise, the normal behavior is that the line should be // trimmed and be considered a real parameter potLines.set(i, potLines.get(i).trim()); } } // Read all of the lines again, create blocks and load them. int counter = 0, endCounter = 1; while (counter < potLines.size()) { // Get the line and shift the counters potLine = potLines.get(counter); ++counter; // The start of a full block is a line with the name in brackets // and without the "./" sequence. if (potLine.contains("[") && potLine.contains("]")) { // Go to the next line potLine = potLines.get(endCounter); // Loop over the block and find the end while (!potLine.contains("[]")) { // Update the line and the counter potLine = potLines.get(endCounter); ++endCounter; } // Create a new block Block block = new Block(); ArrayList<String> blockLines = null; if (endCounter >= counter - 1) { blockLines = new ArrayList<String>(potLines.subList(counter - 1, endCounter)); } if (blockLines != null && !blockLines.isEmpty()) { StringBuilder stringBuilder = new StringBuilder(blockLines.get(0)); blockLines.set(0, stringBuilder.toString()); block.fromGetPot(blockLines); // Add the block to the list trees.add(block.toTreeComposite()); // Update the counter to point to the last read line counter = endCounter; } // Print some debug information if (debugFlag) { logger.info("\nMOOSEFileHandler Message: " + "Block output read from GetPot file " + filePath + " follows."); // Dump each line of the newly created block for (String line : blockLines) { logger.info(line); } } } } } else if (debugFlag) { System.err.println( "MOOSEFileHandler Message: " + "String loaded from " + filePath + " is null or empty."); } return trees; }
From source file:adept.io.Reader.java
/** * Reads specified file into a byte array. * * @param path the path/* w w w.j a v a2s . co m*/ * @return the byte[] */ public byte[] readFileIntoByteArray(String path) { try { RandomAccessFile f = new RandomAccessFile(path, "r"); byte[] b = new byte[(int) f.length()]; f.read(b); f.close(); return b; } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:gate.util.reporting.DocTimeReporter.java
/** * A method for reading the file upside down. * * @param fileToBeRead//from ww w .j a v a2 s . co m * An object of the file to be read. * @param chunkSize * An integer specifying the size of the chunks in which file will be * read. * @return A long value pointing to the start position of the given file * chunk. */ private long tail(File fileToBeRead, int chunkSize) throws BenchmarkReportInputFileFormatException { RandomAccessFile raf = null; try { raf = new RandomAccessFile(fileToBeRead, "r"); Vector<String> lastNlines = new Vector<String>(); int delta = 0; long curPos = 0; curPos = raf.length() - 1; long fromPos; byte[] bytearray; while (true) { fromPos = curPos - chunkSize; if (fromPos <= 0) { raf.seek(0); bytearray = new byte[(int) curPos]; raf.readFully(bytearray); if (parseLinesFromLast(bytearray, lastNlines, fromPos)) { if (fromPos < 0) fromPos = 0; } break; } else { raf.seek(fromPos); bytearray = new byte[chunkSize]; raf.readFully(bytearray); if (parseLinesFromLast(bytearray, lastNlines, fromPos)) { break; } delta = lastNlines.get(lastNlines.size() - 1).length(); lastNlines.remove(lastNlines.size() - 1); curPos = fromPos + delta; } } if (fromPos < 0) throw new BenchmarkReportInputFileFormatException( getBenchmarkFile() + " does not contain a marker named " + getLogicalStart() + " indicating logical start of a run."); return fromPos; } catch (IOException e) { e.printStackTrace(); return -1; } finally { IOUtils.closeQuietly(raf); } }
From source file:org.mhisoft.wallet.service.AttachmentService.java
/** * Append to the existing store for Merged and Created/Updated attachments. * @param filename//from w w w . ja va 2s. c o m * @param model * @param encryptor */ protected void appendAttachmentStore(final String filename, final WalletModel model, final PBEEncryptor encryptor) { FileAccessTable t = new FileAccessTable(); for (WalletItem item : model.getItemsFlatList()) { if (item.getAttachmentEntry() == null) continue; if (item.getAttachmentEntry().getAccessFlag() == FileAccessFlag.Merge) { t.addEntry(item.getAttachmentEntry()); } else if (FileAccessFlag.Create == item.getAttachmentEntry().getAccessFlag() || FileAccessFlag.Update == item.getAttachmentEntry().getAccessFlag()) { if (item.getNewAttachmentEntry() != null && item.getNewAttachmentEntry().getFile() != null) { t.addEntry(item.getNewAttachmentEntry()); } else if (item.getAttachmentEntry().getFile() != null) { t.addEntry(item.getAttachmentEntry()); } } } RandomAccessFile attachmentFileStore = null; try { attachmentFileStore = new RandomAccessFile(filename, "rw"); if (t.getSize() > 0) { //write the total number of entries first int entriesCount = attachmentFileStore.readInt(); //add to be appended ones entriesCount += t.getSize(); attachmentFileStore.seek(0); attachmentFileStore.writeInt(entriesCount); //seek to the end long itemStartPos = attachmentFileStore.length(); attachmentFileStore.seek(itemStartPos); //append new entries to the end of the store. writeFileEntries(model, false, filename, itemStartPos, attachmentFileStore, t, model.getEncryptorForRead(), encryptor); } /*marked the deleted entries **/ for (WalletItem item : model.getItemsFlatList()) { if (item.getAttachmentEntry() == null) continue; if (FileAccessFlag.Delete == item.getAttachmentEntry().getAccessFlag() //the attachment is deleted //the entry had the content saved in the store, now it is replaced. the new content is appended to the end of the file. // the file entry at the old position needs to be marked as DELETE. || (FileAccessFlag.Update == item.getAttachmentEntry().getAccessFlag() && item.getAttachmentEntry().getEncSize() > 0) && item.getAttachmentEntry().getPosition() > 0) { attachmentFileStore.seek(item.getAttachmentEntry().getPosition() + 40); attachmentFileStore.writeInt(FileAccessFlag.Delete.ordinal()); } } attachmentFileStore.close(); attachmentFileStore = null; } catch (IOException e) { e.printStackTrace(); DialogUtils.getInstance().error("Error writing attachment entries.", e.getMessage()); } finally { if (attachmentFileStore != null) try { attachmentFileStore.close(); } catch (IOException e) { //e.printStackTrace(); } } }
From source file:org.gcaldaemon.core.Configurator.java
private final String loadToDoBlock(Request request) throws Exception { String toDoBlock = (String) toDoCache.get(request.url); if (toDoBlock != null) { return toDoBlock; }//ww w . ja va 2s.c o m File file = getToDoFile(request); if (file.exists()) { RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "r"); byte[] bytes = new byte[(int) raf.length()]; raf.readFully(bytes); raf.close(); toDoBlock = StringUtils.decodeToString(bytes, StringUtils.UTF_8); if (toDoCache.size() > MAX_CACHE_SIZE) { toDoCache.clear(); } toDoCache.put(request.url, toDoBlock); return toDoBlock; } catch (Exception ioError) { try { raf.close(); } catch (Exception ignored) { } if (file != null) { file.delete(); } } } return null; }
From source file:com.siblinks.ws.service.impl.MentorServiceImpl.java
/** * {@inheritDoc}/*from w w w. j ava2 s. c o m*/ */ @Override @RequestMapping(value = "/getImageAboutMentor/{id}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) public ResponseEntity<byte[]> getImageAboutMentor(@PathVariable(value = "id") final String id) { ResponseEntity<byte[]> responseEntity = null; try { Map<String, String> queryParams = new HashMap<String, String>(); List<Object> readObject = null; queryParams.put("id", id); String entityName = SibConstants.SqlMapper.SQL_GET_IMAGE_ABOUT_MENTOR; String path = null; readObject = dao.readObjects(entityName, queryParams); if (((Map) readObject.get(0)).get(Parameters.IMAGE) != null) { path = ((Map) readObject.get(0)).get(Parameters.IMAGE).toString(); RandomAccessFile t = null; byte[] r = null; try { t = new RandomAccessFile(path, "r"); r = new byte[(int) t.length()]; t.readFully(r); responseEntity = new ResponseEntity<byte[]>(r, new HttpHeaders(), HttpStatus.OK); } catch (IOException e) { logger.debug("Some thing wrong", e); responseEntity = new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND); } finally { // Close file if (t != null) { try { t.close(); } catch (IOException e) { // Do nothing } } } } else { responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT); } } catch (DAOException e) { e.printStackTrace(); new SimpleResponse(SibConstants.FAILURE, "Mentor", "getImageAboutMentor", e.getMessage()); } return responseEntity; }
From source file:com.android.volley.toolbox.UploadNetwork.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 w w w.j a v a 2 s.com 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 String url = requestDown.getUrl(); String name = url.substring(url.lastIndexOf('/'), url.length()); String path = requestDown.getDownloadPath(); String filePath = ""; if (path.endsWith("/")) { filePath = path + name; } else { path = path + "/"; filePath = path + "/" + name; } File dir = new File(path); dir.mkdirs(); file = File.createTempFile(path, null, dir); acessfile = new RandomAccessFile(file, "rws"); long length = acessfile.length(); acessfile.seek(length); // Range: bytes=5275648- 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(); file.renameTo(new File(filePath)); return new NetworkResponse(statusCode, responseContents, 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:ar.com.qbe.siniestros.model.utils.MimeMagic.MagicMatcher.java
/** * test to see if this match or any submatches match * * @param f the file that should be used to test the match * @param onlyMimeMatch DOCUMENT ME!/* ww w . j ava2s.co m*/ * * @return the deepest magic match object that matched * * @throws IOException DOCUMENT ME! * @throws UnsupportedTypeException DOCUMENT ME! */ public MagicMatch test(File f, boolean onlyMimeMatch) throws IOException, UnsupportedTypeException { log.debug("test(File)"); int offset = match.getOffset(); String description = match.getDescription(); String type = match.getType(); String mimeType = match.getMimeType(); log.debug("test(File): testing '" + f.getName() + "' for '" + description + "'"); log.debug("test(File): \n=== BEGIN MATCH INFO =="); log.debug(match.print()); log.debug("test(File): \n=== END MATCH INFO ====\n"); RandomAccessFile file = null; file = new RandomAccessFile(f, "r"); try { int length = 0; if (type.equals("byte")) { length = 1; } else if (type.equals("short") || type.equals("leshort") || type.equals("beshort")) { length = 4; } else if (type.equals("long") || type.equals("lelong") || type.equals("belong")) { length = 8; } else if (type.equals("string")) { length = match.getTest().capacity(); } else if (type.equals("regex")) { final int matchLength = match.getLength(); length = (matchLength == 0) ? (int) file.length() - offset : matchLength; if (length < 0) { length = 0; } } else if (type.equals("detector")) { length = (int) file.length() - offset; if (length < 0) { length = 0; } } else { throw new UnsupportedTypeException("unsupported test type '" + type + "'"); } // we know this match won't work since there isn't enough data for the test if (length > (file.length() - offset)) { return null; } byte[] buf = new byte[length]; file.seek(offset); int bytesRead = 0; int size = 0; boolean gotAllBytes = false; boolean done = false; while (!done) { size = file.read(buf, 0, length - bytesRead); if (size == -1) { throw new IOException("reached end of file before all bytes were read"); } bytesRead += size; if (bytesRead == length) { gotAllBytes = true; done = true; } } log.debug("test(File): stream size is '" + buf.length + "'"); MagicMatch match = null; MagicMatch submatch = null; if (testInternal(buf)) { // set the top level match to this one try { match = getMatch() != null ? (MagicMatch) getMatch().clone() : null; } catch (CloneNotSupportedException e) { // noop } log.debug("test(File): testing matched '" + description + "'"); // set the data on this match if ((onlyMimeMatch == false) && (subMatchers != null) && (subMatchers.size() > 0)) { log.debug( "test(File): testing " + subMatchers.size() + " submatches for '" + description + "'"); for (int i = 0; i < subMatchers.size(); i++) { log.debug("test(File): testing submatch " + i); MagicMatcher m = (MagicMatcher) subMatchers.get(i); if ((submatch = m.test(f, false)) != null) { log.debug("test(File): submatch " + i + " matched with '" + submatch.getDescription() + "'"); match.addSubMatch(submatch); } else { log.debug("test(File): submatch " + i + " doesn't match"); } } } } return match; } finally { try { file.close(); } catch (Exception fce) { } } }