List of usage examples for java.io FileInputStream skip
public long skip(long n) throws IOException
n
bytes of data from the input stream. From source file:savant.util.CachedSeekableStream.java
private void cachedSeek(int blockOffset, int positionOffset) throws IOException { //from offset, calculate actual position in file long actualOffset = (numBlocks * 4L) + (blockOffset - 1L) * bufferSize; //retrieve from stream FileInputStream cacheStream = new FileInputStream(cacheFile); try {/* w w w .j a va 2 s .c o m*/ cacheStream.skip(actualOffset); bufferedStream.close(); bufferedStream = new BufferedInputStream(cacheStream, bufferSize); bufferedStream.skip(positionOffset); positionInBuf = positionOffset; } catch (IOException x) { throw x; } }
From source file:org.taverna.server.localworker.impl.FileDelegate.java
@Override public byte[] getContents(int offset, int length) throws IOException { if (length == -1) length = (int) (file.length() - offset); if (length < 0 || length > 1024 * 64) length = 1024 * 64;/*from w w w.j a v a2s . c o m*/ byte[] buffer = new byte[length]; FileInputStream fis = null; int read; try { fis = new FileInputStream(file); if (offset > 0) if (fis.skip(offset) != offset) throw new IOException("did not move to correct offset in file"); read = fis.read(buffer); } finally { if (fis != null) fis.close(); } if (read <= 0) return new byte[0]; if (read < buffer.length) { byte[] shortened = new byte[read]; arraycopy(buffer, 0, shortened, 0, read); return shortened; } return buffer; }
From source file:com.wifi.brainbreaker.mydemo.http.ModAssetServer.java
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { AbstractHttpEntity body = null;/*w w w . ja v a 2 s . co m*/ final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } final String url = URLDecoder.decode(request.getRequestLine().getUri()); if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length); } final String location = "www" + (url.equals("/") ? "/index.htm" : url); response.setStatusCode(HttpStatus.SC_OK); try { Log.i(TAG, "Requested: \"" + url + "\""); // Compares the Last-Modified date header (if present) with the If-Modified-Since date if (request.containsHeader("If-Modified-Since")) { try { Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue()); if (date.compareTo(mServer.mLastModified) <= 0) { // The file has not been modified response.setStatusCode(HttpStatus.SC_NOT_MODIFIED); return; } } catch (DateParseException e) { e.printStackTrace(); } } // We determine if the asset is compressed try { AssetFileDescriptor afd = mAssetManager.openFd(location); // The asset is not compressed FileInputStream fis = new FileInputStream(afd.getFileDescriptor()); fis.skip(afd.getStartOffset()); body = new InputStreamEntity(fis, afd.getDeclaredLength()); Log.d(TAG, "Serving uncompressed file " + "www" + url); } catch (FileNotFoundException e) { // The asset may be compressed // AAPT compresses assets so first we need to uncompress them to determine their length InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING); ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000); byte[] tmp = new byte[4096]; int length = 0; while ((length = stream.read(tmp)) != -1) buffer.write(tmp, 0, length); body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size()); stream.close(); Log.d(TAG, "Serving compressed file " + "www" + url); } body.setContentType(getMimeMediaType(url) + "; charset=UTF-8"); response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified)); } catch (IOException e) { // File does not exist response.setStatusCode(HttpStatus.SC_NOT_FOUND); body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write("<html><body><h1>"); writer.write("File "); writer.write("www" + url); writer.write(" not found"); writer.write("</h1></body></html>"); writer.flush(); } }); Log.d(TAG, "File " + "www" + url + " not found"); body.setContentType("text/html; charset=UTF-8"); } response.setEntity(body); }
From source file:net.facework.core.http.ModAssetServer.java
@Override public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { AbstractHttpEntity body = null;/*from ww w . j a v a 2s . c om*/ final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } final String url = URLDecoder.decode(request.getRequestLine().getUri()); if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length); } final String location = "www" + (url.equals("/") ? "/index.htm" : url); response.setStatusCode(HttpStatus.SC_OK); try { Log.i(TAG, "Requested: \"" + url + "\""); // Compares the Last-Modified date header (if present) with the If-Modified-Since date if (request.containsHeader("If-Modified-Since")) { try { Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue()); if (date.compareTo(mServer.mLastModified) <= 0) { // The file has not been modified response.setStatusCode(HttpStatus.SC_NOT_MODIFIED); return; } } catch (DateParseException e) { e.printStackTrace(); } } // We determine if the asset is compressed try { AssetFileDescriptor afd = mAssetManager.openFd(location); // The asset is not compressed FileInputStream fis = new FileInputStream(afd.getFileDescriptor()); fis.skip(afd.getStartOffset()); body = new InputStreamEntity(fis, afd.getDeclaredLength()); Log.d(TAG, "Serving uncompressed file " + "www" + url); } catch (FileNotFoundException e) { // The asset may be compressed // AAPT compresses assets so first we need to uncompress them to determine their length InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING); ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000); byte[] tmp = new byte[4096]; int length = 0; while ((length = stream.read(tmp)) != -1) buffer.write(tmp, 0, length); body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size()); stream.close(); Log.d(TAG, "Serving compressed file " + "www" + url); } body.setContentType(getMimeMediaType(url) + "; charset=UTF-8"); response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified)); } catch (IOException e) { // File does not exist response.setStatusCode(HttpStatus.SC_NOT_FOUND); body = new EntityTemplate(new ContentProducer() { @Override public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write("<html><body><h1>"); writer.write("File "); writer.write("www" + url); writer.write(" not found"); writer.write("</h1></body></html>"); writer.flush(); } }); Log.d(TAG, "File " + "www" + url + " not found"); body.setContentType("text/html; charset=UTF-8"); } response.setEntity(body); }
From source file:com.baidu.terminator.storage.file.FileStorage.java
public Object getbyID(Long dataId) { // load from database DataIndex recordData = dataIndexMapper.selectDataIndexByID(dataId); RequestResponseBundle bundles = new RequestResponseBundle(); // read from file if (recordData != null) { Long offset;//from w ww . ja v a2 s . com offset = recordData.getOffset(); String filePath = this.filePath; try { FileInputStream dataStream = new FileInputStream(filePath); dataStream.skip(offset); ObjectInputStream objStream = new ObjectInputStream(dataStream); bundles = (RequestResponseBundle) objStream.readObject(); objStream.close(); dataStream.close(); } catch (Exception e) { logger.error("[UPDATE] file data does not exists"); System.out.println("[UPDATE] file data does not exists!"); e.printStackTrace(); } } return bundles; }
From source file:com.baidu.terminator.storage.file.FileStorage.java
@Override public RequestResponseBundle getRecordData(String key) { // load record offset from database HashMap<String, Object> parameters = new HashMap<String, Object>(); parameters.put("linkId", link.getId()); parameters.put("signature", key); DataIndex recordData = dataIndexMapper.selectDataIndex(parameters); // read data record from file RequestResponseBundle bundles = new RequestResponseBundle(); if (recordData != null) { logger.info("[GET] the request hit the file storage!"); Long offset = recordData.getOffset(); FileInputStream fis = null; ObjectInputStream ois = null; try {//from w w w .ja va 2s.c o m fis = new FileInputStream(filePath); fis.skip(offset); ois = new ObjectInputStream(fis); bundles = (RequestResponseBundle) ois.readObject(); } catch (FileNotFoundException e) { logger.error("[GET] can not find data file: " + filePath, e); } catch (IOException e) { logger.error("[GET] data record from storage in file fail!", e); } catch (ClassNotFoundException e) { logger.error("[GET] data record from storage in file fail!", e); } finally { try { if (ois != null) { ois.close(); } if (fis != null) { fis.close(); } } catch (IOException e) { logger.error("[GET] close file output stream error", e); } } } else { logger.info("[GET] the request does not hit the file storage!"); } return bundles; }
From source file:org.dcm4che.tool.storescu.StoreSCU.java
public void send(final File f, long fmiEndPos, String cuid, String iuid, String ts) throws IOException, InterruptedException { if (uidSuffix == null && attrs.isEmpty()) { FileInputStream in = new FileInputStream(f); try {/*from w w w.ja va 2 s .com*/ in.skip(fmiEndPos); InputStreamDataWriter data = new InputStreamDataWriter(in); as.cstore(cuid, iuid, priority, data, ts, rspHandler(f)); } finally { SafeClose.close(in); } } else { DicomInputStream in = new DicomInputStream(f); try { in.setIncludeBulkData(IncludeBulkData.URI); Attributes data = in.readDataset(-1, -1); if (CLIUtils.updateAttributes(data, attrs, uidSuffix)) iuid = data.getString(Tag.SOPInstanceUID); as.cstore(cuid, iuid, priority, new DataWriterAdapter(data), ts, rspHandler(f)); } finally { SafeClose.close(in); } } }
From source file:io.pravega.segmentstore.storage.impl.extendeds3.S3FileSystemImpl.java
@Override public InputStream readObjectStream(String bucketName, String key, Range range) { byte[] bytes = new byte[Math.toIntExact(range.getLast() + 1 - range.getFirst())]; Path path = Paths.get(this.baseDir, bucketName, key); FileInputStream returnStream; try {/*from w w w . j a v a 2 s .co m*/ returnStream = new FileInputStream(path.toFile()); if (range.getFirst() != 0) { long bytesSkipped = 0; do { bytesSkipped += returnStream.skip(range.getFirst()); } while (bytesSkipped < range.getFirst()); } StreamHelpers.readAll(returnStream, bytes, 0, bytes.length); return new ByteArrayInputStream(bytes); } catch (IOException e) { throw new S3Exception("NoSuchKey", HttpStatus.SC_NOT_FOUND, "NoSuchKey", ""); } }
From source file:com.jpeterson.util.http.RangeInputStreamTest.java
/** * Simple test of the <code>FileInputStream</code> <code>skip()</code> * method. I was trying to verify what return value the skip() provides when * you skip past the actual content size. *//*ww w. j ava2 s . c o m*/ public void xtest_skip() { long count; FileInputStream in; File file = new File("C:/temp/foo.txt"); try { in = new FileInputStream(file); count = in.skip(10); System.out.println("Count of skipping '10' first: " + count); count = in.skip(10); System.out.println("Count of skipping '10' second: " + count); count = in.skip(10); System.out.println("Count of skipping '10' third: " + count); count = in.skip(10); System.out.println("Count of skipping '10' fourth: " + count); count = in.skip(10); System.out.println("Count of skipping '10' fifth: " + count); System.out.println("Read: " + in.read()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:net.fenyo.gnetwatch.actions.ActionGenericSrc.java
/** * Get data from the external source./* w w w . j av a 2s. c o m*/ * @param none. * @return void. * @throws IOException IO exception. * @throws InterruptedException exception. */ // Queue thread // supports any thread public void invoke() throws IOException, InterruptedException { if (isDisposed() == true) return; try { super.invoke(); if (TargetGroup.class.isInstance(getTarget())) { GenericQuerier querier; synchronized (getGUI().getSynchro()) { querier = (GenericQuerier) ((TargetGroup) getTarget()).getGenericQuerier().clone(); } getGUI().setStatus(getGUI().getConfig().getPattern("reading_file", querier.getFileName())); if (last_file_size == -1) { last_file_size = new File(querier.getFileName()).length(); return; } // lire le contenu du fichier int value = -10; int value1 = -10; int value2 = -10; int value3 = -10; int value4 = -10; int value5 = -10; int value6 = -10; int value7 = -10; int value8 = -10; int value9 = -10; int value10 = -10; String units = ""; boolean value_ok = false; final File file = new File(querier.getFileName()); final long new_file_size = file.length(); if (last_file_size == new_file_size) return; last_file_size = new_file_size; FileInputStream byte_stream = null; try { byte_stream = new FileInputStream(file); byte_stream.skip(Math.max(0, last_file_size - 300)); // we want each char having 1 byte length, so we choose US-ASCII character encoding final InputStreamReader char_stream = new InputStreamReader(byte_stream, "US-ASCII"); final char ctab[] = new char[300]; final int nchars = char_stream.read(ctab, 0, 300); if (nchars > 0) { Matcher match = Pattern.compile( "<([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([^>]*)>.*?$") .matcher(new String(ctab, 0, nchars)); if (match.find()) { value1 = new Integer(match.group(1)); value2 = new Integer(match.group(2)); value3 = new Integer(match.group(3)); value4 = new Integer(match.group(4)); value5 = new Integer(match.group(5)); value6 = new Integer(match.group(6)); value7 = new Integer(match.group(7)); value8 = new Integer(match.group(8)); value9 = new Integer(match.group(9)); value10 = new Integer(match.group(10)); units = match.group(11); value_ok = true; } else { match = Pattern.compile("([0-9]+).*?$").matcher(new String(ctab, 0, nchars)); if (match.find()) { value = new Integer(match.group(1)); value_ok = true; } } } } finally { if (byte_stream != null) byte_stream.close(); } synchronized (getGUI().getSynchro()) { synchronized (getGUI().sync_tree) { final Session session = getGUI().getSynchro().getSessionFactory().getCurrentSession(); session.beginTransaction(); try { session.update(this); // pour le setDescription() => enlever qd la description ne sera plus persistente if (value_ok) { getTarget().addEvent(new EventGenericSrc(true, value, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10, units)); getGUI().setStatus(getGUI().getConfig().getPattern("new_file_value", GenericTools.formatNumericString(getGUI().getConfig(), new Integer(value < 0 ? value1 : value).toString()))); setDescription("" + GenericTools.formatNumericString(getGUI().getConfig(), new Integer(value < 0 ? value1 : value).toString()) + " " + querier.getUnit()); } else { // getTarget().addEvent(new EventGenericSrc(false)); getGUI().setStatus(getGUI().getConfig().getString("new_file_value_incorrect")); setDescription(getGUI().getConfig().getString("new_file_value_incorrect")); } session.getTransaction().commit(); } catch (final Exception ex) { log.error("Exception", ex); session.getTransaction().rollback(); } } } } } catch (final InterruptedException ex) { synchronized (getGUI().getSynchro()) { synchronized (getGUI().sync_tree) { final Session session = getGUI().getSynchro().getSessionFactory().getCurrentSession(); session.beginTransaction(); try { session.update(this); // pour le setDescription() => enlever qd la description ne sera plus persistente getTarget().addEvent(new EventGenericSrc(false)); // mettre un setstatus comme pour IPv4 // setDescription(getGUI().getConfig().getString("unreachable")); session.getTransaction().commit(); } catch (final Exception ex2) { log.error("Exception", ex2); session.getTransaction().rollback(); } } } throw ex; } }