java.io.InputStream#close ( )源码实例Demo

下面列出了java.io.InputStream#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

public void setup() throws UserStoreException {

        try {
            RealmConfigXMLProcessor builder = new RealmConfigXMLProcessor();
            InputStream inStream = this.getClass().getResourceAsStream("/users/user-mgt-users.xml");

            try {
                this.bootstrapRealmConfig = builder.buildRealmConfiguration(inStream);
            } finally {
                inStream.close();
            }
        } catch (Exception e) {
            String msg = "Failed to initialize the user manager. ";
            throw new UserStoreException(msg, e);
        }

        this.tenantManager = new InMemoryTenantManager();
    }
 
源代码2 项目: olat   文件: DefaultServlet.java
/**
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an
 * exception).
 * 
 * @param istream
 *            The input stream to read from
 * @param ostream
 *            The output stream to write to
 * @exception IOException
 *                if an input/output error occurs
 */
private void copy(ResourceInfo resourceInfo, ServletOutputStream ostream) throws IOException {

    IOException exception = null;

    // FIXME:ms: i18n ?
    InputStream resourceInputStream = resourceInfo.getStream();
    InputStream istream = new BufferedInputStream(resourceInputStream, input);

    // Copy the input stream to the output stream
    exception = copyRange(istream, ostream);

    // Clean up the input stream
    try {
        istream.close();
    } catch (Throwable t) {

    }

    // Rethrow any exception that has occurred
    if (exception != null)
        throw exception;

}
 
源代码3 项目: Cubert   文件: AvroStorage.java
/**
 * This method is called to return the schema of an avro schema file. This
 * method is different than {@link #getSchema}, which returns the schema
 * from a data file.
 *
 * @param path  path of a file or first level directory
 * @param fs  file system
 * @return avro schema
 * @throws IOException
 */
protected Schema getSchemaFromFile(Path path, FileSystem fs) throws IOException {
    /* get path of the last file */
    Path lastFile = AvroStorageUtils.getLast(path, fs);
    if (lastFile == null) {
        return null;
    }

    /* read in file and obtain schema */
    GenericDatumReader<Object> avroReader = new GenericDatumReader<Object>();
    InputStream hdfsInputStream = fs.open(lastFile);
    Schema ret = Schema.parse(hdfsInputStream);
    hdfsInputStream.close();

    return ret;
}
 
源代码4 项目: cloud-espm-v2   文件: StreamHelper.java
/**
 * Read File content
 * 
 * @param fileName
 * @return file content as String
 * @throws IOException
 */
public static String readFromFile(String fileName) {
	InputStream in = null;
	String result = null;
	ClassLoader cLoader = RequestExecutionHelper.class.getClassLoader();
	if (cLoader != null) {
		try {
			in = cLoader.getResourceAsStream(fileName);
			result = StreamHelper.readStreamContent(in);

		} catch (IOException ex) {
			LOGGER.error(ex.getMessage());
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				LOGGER.error(e.getMessage());

			}
		}

	}
	return result;

}
 
源代码5 项目: openjdk-jdk8u-backup   文件: Source.java
static byte[] readBytes(final InputStream is) throws IOException {
    final byte[] arr = new byte[BUF_SIZE];
    try {
        try (ByteArrayOutputStream buf = new ByteArrayOutputStream()) {
            int numBytes;
            while ((numBytes = is.read(arr, 0, arr.length)) > 0) {
                buf.write(arr, 0, numBytes);
            }
            return buf.toByteArray();
        }
    } finally {
        is.close();
    }
}
 
源代码6 项目: hadoop   文件: CryptoStreamsTestBase.java
private void cryptoCheck(byte[] iv) throws Exception {
  OutputStream out = getOutputStream(defaultBufferSize, key, iv);
  writeData(out);
  
  InputStream in = getInputStream(defaultBufferSize, key, iv);
  readCheck(in);
  in.close();
}
 
源代码7 项目: TVRemoteIME   文件: HTTPGet.java
public static boolean downloadFile(String uri, File file){
    HTTPSTrustManager.allowAllSSL();
    try {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "text/html, application/xhtml+xml, image/jxr, */*");
        conn.setRequestProperty("Accept-Encoding", "identity");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");

        int code = conn.getResponseCode();
        if (code == 200) {
            InputStream instream = conn.getInputStream();
            FileOutputStream fos = new FileOutputStream(file);
            try {
                byte[] tmp = new byte[4096];

                int l;
                while((l = instream.read(tmp)) != -1) {
                    fos.write(tmp, 0, l);
                }
                return true;
            } finally {
                instream.close();
                fos.close();
            }
        } else {
            return false;
        }
    } catch (Exception e) {
        Log.e("HTTPGet", "downloadFile", e);
    }
    return false;
}
 
源代码8 项目: jobcacher-plugin   文件: Uploads.java
private void closeStream(File file, InputStream inputStream) {
    try {
        if (inputStream != null) {
            inputStream.close();
        }
    } catch (IOException e) {
        LOGGER.warning("Failed to close stream for file:" + file);
    }
}
 
源代码9 项目: lams   文件: StateMachineParser.java
private void safeClose(InputStream fis)
{
   try
   {
      if(fis != null)
      {
         fis.close();
      }
   }
   catch(Exception e)
   {}
}
 
源代码10 项目: justtestlah   文件: LocatorPlaceholders.java
private Properties loadProperties(InputStream input) {
  Properties props = new Properties();
  if (input == null) {
    LOG.warn("Could not load placeholders");
    return props;
  }
  try {
    props.load(input);
    input.close();
  } catch (IOException exception) {
    LOG.warn("Could not load placeholders");
  }
  return props;
}
 
源代码11 项目: cacheonix-core   文件: IOUtils.java
/**
 * Closes input stream regardless of thrown exception
 */
public static void closeHard(final InputStream is) {

   if (is != null) {
      try {
         is.close();
      } catch (final IOException e) {
         logCloseWarning(e);
      }
   }
}
 
源代码12 项目: jmonkeyengine   文件: XMLImporter.java
@Override
public Object load(AssetInfo info) throws IOException {
    assetManager = info.getManager();
    InputStream in = info.openStream();
    try {
        return load(in);
    } finally {
        if (in != null)
            in.close();
    }
}
 
源代码13 项目: jparsec   文件: IoUtils.java
public static String read(URL url) throws IOException {
  InputStream in = url.openStream();
  try {
    return read(new InputStreamReader(in, Charset.forName("UTF-8")));
  } finally {
    in.close();
  }
}
 
源代码14 项目: gemfirexd-oss   文件: QueryPerfClient.java
public static byte[] getBytesFromFile(File file) throws IOException {
  InputStream is = new FileInputStream(file);

  // Get the size of the file
  long length = file.length();
  if (length > Integer.MAX_VALUE)
    throw new TestException("input file is too long");

  byte[] bytes = new byte[(int)length];

  // Read in the bytes
  int offset = 0;
  int numRead = 0;
  while (offset < bytes.length
         && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
      offset += numRead;
  }

  // Ensure all the bytes have been read in
  if (offset < bytes.length) {
      throw new IOException("Could not completely read file "+file.getName());
  }

  // Close the input stream and return bytes
  is.close();
  return bytes;
}
 
源代码15 项目: ermasterr   文件: IOUtils.java
public static void closeQuietly(final InputStream input) {
    try {
        if (input != null)
            input.close();
    } catch (final IOException ioe) {}
}
 
源代码16 项目: hop   文件: XmlInputFieldsImportProgressDialog.java
@SuppressWarnings( "unchecked" )
private RowMetaAndData[] doScan( IProgressMonitor monitor ) throws Exception {
  monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ScanningFile",
      filename ), 1 );

  SAXReader reader = XmlParserFactoryProducer.getSAXReader( null );
  monitor.worked( 1 );
  if ( monitor.isCanceled() ) {
    return null;
  }
  // Validate XML against specified schema?
  if ( meta.isValidating() ) {
    reader.setValidation( true );
    reader.setFeature( "http://apache.org/xml/features/validation/schema", true );
  } else {
    // Ignore DTD
    reader.setEntityResolver( new IgnoreDtdEntityResolver() );
  }
  monitor.worked( 1 );
  monitor
      .beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingDocument" ), 1 );
  if ( monitor.isCanceled() ) {
    return null;
  }
  InputStream is = null;
  try {

    Document document = null;
    if ( !Utils.isEmpty( filename ) ) {
      is = HopVfs.getInputStream( filename );
      document = reader.read( is, encoding );
    } else {
      if ( !Utils.isEmpty( xml ) ) {
        document = reader.read( new StringReader( xml ) );
      } else {
        document = reader.read( new URL( url ) );
      }
    }

    monitor.worked( 1 );
    monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.DocumentOpened" ),
        1 );
    monitor.worked( 1 );
    monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingNode" ), 1 );

    if ( monitor.isCanceled() ) {
      return null;
    }
    List<Node> nodes = document.selectNodes( this.loopXPath );
    monitor.worked( 1 );
    monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes" ) );

    if ( monitor.isCanceled() ) {
      return null;
    }
    for ( Node node : nodes ) {
      if ( monitor.isCanceled() ) {
        return null;
      }

      nr++;
      monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes", String
          .valueOf( nr ) ) );
      monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes", node
          .getPath() ) );
      setNodeField( node, monitor );
      childNode( node, monitor );

    }
    monitor.worked( 1 );
  } finally {
    try {
      if ( is != null ) {
        is.close();
      }
    } catch ( Exception e ) { /* Ignore */
    }
  }

  RowMetaAndData[] listFields = fieldsList.toArray( new RowMetaAndData[fieldsList.size()] );

  monitor.setTaskName( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.NodesReturned" ) );

  monitor.done();

  return listFields;

}
 
源代码17 项目: cuba   文件: CubaWebJarsHandler.java
@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException {
    String path = request.getPathInfo();
    if (StringUtils.isEmpty(path)
            || !path.startsWith(VAADIN_WEBJARS_PATH_PREFIX)) {
        return false;
    }

    log.trace("WebJar resource requested: {}", path.replace(VAADIN_WEBJARS_PATH_PREFIX, ""));

    String errorMessage = checkResourcePath(path);
    if (StringUtils.isNotEmpty(errorMessage)) {
        log.warn(errorMessage);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, errorMessage);
        return false;
    }

    URL resourceUrl = getStaticResourceUrl(path);

    if (resourceUrl == null) {
        resourceUrl = getClassPathResourceUrl(path);
    }

    if (resourceUrl == null) {
        String msg = String.format("Requested WebJar resource is not found: %s", path);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        log.warn(msg);
        return false;
    }

    String resourceName = getResourceName(path);
    String mimeType = servletContext.getMimeType(resourceName);
    response.setContentType(mimeType != null ? mimeType : FileTypesHelper.DEFAULT_MIME_TYPE);

    long resourceCacheTime = getCacheTime();

    String cacheControl = resourceCacheTime > 0
            ? "max-age=" + String.valueOf(resourceCacheTime)
            : "public, max-age=0, no-cache, no-store, must-revalidate";
    response.setHeader("Cache-Control", cacheControl);

    long expires = resourceCacheTime > 0
            ? System.currentTimeMillis() + (resourceCacheTime * 1000)
            : 0;
    response.setDateHeader("Expires", expires);

    InputStream inputStream = null;
    try {
        URLConnection connection = resourceUrl.openConnection();
        long lastModifiedTime = connection.getLastModified();
        // Remove milliseconds to avoid comparison problems (milliseconds
        // are not returned by the browser in the "If-Modified-Since"
        // header).
        lastModifiedTime = lastModifiedTime - lastModifiedTime % 1000;
        response.setDateHeader("Last-Modified", lastModifiedTime);

        if (browserHasNewestVersion(request, lastModifiedTime)) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return true;
        }

        inputStream = connection.getInputStream();

        copy(inputStream, response.getOutputStream());

        return true;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}
 
源代码18 项目: gemfirexd-oss   文件: LobStreamsTest.java
/**
 * Tests the ClobOutputStream.write(byte  b[], int off, int len) method
 **/
public void testClobAsciiWrite3Param() throws Exception {
    InputStream streamIn = new LoopingAlphabetStream(streamSize[0]);
    assertTrue("FAIL -- file not found", streamIn != null);

    PreparedStatement stmt3 = prepareStatement(
        "SELECT c FROM testBlobX1 WHERE a = 1");
    ResultSet rs3 = stmt3.executeQuery();
    rs3.next();
    Clob clob = rs3.getClob(1);

    assertTrue("FAIL -- clob is NULL", clob != null);

    int count = 0;
    byte[] buffer = new byte[1024];
    OutputStream outstream = clob.setAsciiStream(1L);
    while ((count = streamIn.read(buffer)) != -1) {
        outstream.write(buffer, 0, count);
    }
    outstream.close();
    streamIn.close();

    PreparedStatement stmt4 = prepareStatement(
        "UPDATE testBlobX1 SET c = ? WHERE a = 1");
    stmt4.setClob(1,  clob);
    stmt4.executeUpdate();
    stmt4.close();

    rs3.close();
    rs3 = stmt3.executeQuery();

    assertTrue("FAIL -- clob not found", rs3.next());

    long new_length = rs3.getClob(1).length();
    assertEquals("FAIL -- wrong clob length",
            streamSize[0], new_length);
    // Check contents ...
    InputStream fStream = new LoopingAlphabetStream(streamSize[0]);
    InputStream lStream = rs3.getClob(1).getAsciiStream();
    assertTrue("FAIL - Clob and file contents do not match",
            compareLob2File(fStream, lStream));

    fStream.close();
    lStream.close();
    rs3.close();
    stmt3.close();
}
 
源代码19 项目: gemfirexd-oss   文件: ClientConfiguration.java
protected ClientConfiguration(String resourceName) {
  this.resourceName = resourceName;

  Properties props = new Properties();
  InputStream is = getClass().getClassLoader().getResourceAsStream(
      resourceName);
  if (is == null) {
    is = ClassLoader.getSystemResourceAsStream(resourceName);
  }
  if (is == null) {
    this.error = "<Could not find resource " + resourceName + '>';
    return;
  }
  else {
    try {
      props.load(is);
      is.close();
    } catch (Exception ex) {
      this.error = "<Could not read properties from resource "
          + resourceName + " because: " + ex + '>';
      return;
    }
  }

  this.productName = props.getProperty(PRODUCT_NAME);
  this.productVersion = props.getProperty(GEMFIRE_VERSION);
  // below setting for GemFireXD is to indicate the underlying GemFire
  // version being used in GemFireXD product; for GemFire this will not
  // be set and instead this.productVersion is used where required
  String gfVersion = props.getProperty(UNDERLYING_GEMFIRE_VERSION);
  // special token "NOT SET" might be present that indicates no separate
  // GemFire version
  if (gfVersion != null && gfVersion.startsWith("NOT SET")) {
    gfVersion = null;
  }
  this.gemfireVersion = gfVersion;

  this.sourceDate = props.getProperty(SOURCE_DATE);
  this.sourceRevision = props.getProperty(SOURCE_REVISION);
  this.sourceRepository = props.getProperty(SOURCE_REPOSITORY);
  this.buildDate = props.getProperty(BUILD_DATE);
  this.buildId = props.getProperty(BUILD_ID);
  this.buildPlatform = props.getProperty(BUILD_PLATFORM);
  this.buildJavaVersion = props.getProperty(BUILD_JAVA_VERSION);
}
 
源代码20 项目: openjdk-jdk8u-backup   文件: Properties.java
/**
 * Loads all of the properties represented by the XML document on the
 * specified input stream into this properties table.
 *
 * <p>The XML document must have the following DOCTYPE declaration:
 * <pre>
 * &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt;
 * </pre>
 * Furthermore, the document must satisfy the properties DTD described
 * above.
 *
 * <p> An implementation is required to read XML documents that use the
 * "{@code UTF-8}" or "{@code UTF-16}" encoding. An implementation may
 * support additional encodings.
 *
 * <p>The specified stream is closed after this method returns.
 *
 * @param in the input stream from which to read the XML document.
 * @throws IOException if reading from the specified input stream
 *         results in an <tt>IOException</tt>.
 * @throws java.io.UnsupportedEncodingException if the document's encoding
 *         declaration can be read and it specifies an encoding that is not
 *         supported
 * @throws InvalidPropertiesFormatException Data on input stream does not
 *         constitute a valid XML document with the mandated document type.
 * @throws NullPointerException if {@code in} is null.
 * @see    #storeToXML(OutputStream, String, String)
 * @see    <a href="http://www.w3.org/TR/REC-xml/#charencoding">Character
 *         Encoding in Entities</a>
 * @since 1.5
 */
public synchronized void loadFromXML(InputStream in)
    throws IOException, InvalidPropertiesFormatException
{
    XmlSupport.load(this, Objects.requireNonNull(in));
    in.close();
}