下面列出了怎么用java.io.Closeable的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 关闭流
*
* @param closeables
*/
public static void closeIO(Closeable... closeables) {
if (null == closeables || closeables.length <= 0) {
return;
}
for (Closeable cb : closeables) {
try {
if (null == cb) {
continue;
}
cb.close();
} catch (IOException e) {
Log.e(TAG, "close IO ERROR...", e);
}
}
}
@Test
public void testAcquireUsingWithCharSequence() throws IOException {
ChronicleMapBuilder<CharSequence, CharSequence> builder = ChronicleMapBuilder
.of(CharSequence.class, CharSequence.class)
.entries(1);
try (ChronicleMap<CharSequence, CharSequence> map = newInstance(builder)) {
CharSequence using = new StringBuilder();
try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext("1", using)) {
assertTrue(using instanceof StringBuilder);
((StringBuilder) using).append("Hello World");
}
assertEquals("Hello World", map.get("1").toString());
mapChecks();
}
}
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("please specify wsdl");
System.exit(1);
}
File wsdl = new File(args[0]);
JMSGreeterService service = new JMSGreeterService(wsdl.toURI().toURL(), SERVICE_NAME);
JMSGreeterPortType greeter = (JMSGreeterPortType)service.getPort(PORT_NAME, JMSGreeterPortType.class);
System.out.println("Invoking greetMeOneWay...");
greeter.greetMeOneWay(System.getProperty("user.name"));
System.out.println("No response from server as method is OneWay");
System.out.println();
if (greeter instanceof Closeable) {
((Closeable)greeter).close();
}
System.exit(0);
}
/**
* Tests write operations followed by seek operations.
*
* @throws IOException should never happen since we read and write in memory only.
*/
@Test
@DependsOnMethod("testAllWriteMethods")
public void testWriteAndSeek() throws IOException {
initialize("testWriteAndSeek", STREAM_LENGTH, random.nextInt(BUFFER_MAX_CAPACITY) + Double.BYTES);
writeInStreams();
((Closeable) referenceStream).close();
final byte[] expectedArray = expectedData.toByteArray();
final int seekRange = expectedArray.length - Long.BYTES;
final ByteBuffer arrayView = ByteBuffer.wrap(expectedArray);
for (int i=0; i<100; i++) {
final int position = random.nextInt(seekRange);
testedStream.seek(position);
assertEquals("getStreamPosition()", position, testedStream.getStreamPosition());
final long v = random.nextLong();
testedStream.writeLong(v);
arrayView.putLong(position, v);
}
testedStream.flush();
assertArrayEquals(expectedArray, Arrays.copyOf(testedStreamBackingArray, expectedArray.length));
}
@Override
public void close() {
// 单例工厂中,如果为closeable的,关闭
synchronized (SINGLE_FACTORY) {
SINGLE_FACTORY.forEach((k, v) -> {
if (v instanceof Closeable) {
Closeable cl = (Closeable) v;
try {
cl.close();
QQLog.debug("depend.center.close", k);
} catch (IOException e) {
QQLog.error("depend.center.close.failed", e, k, v.getClass(), e.getLocalizedMessage());
}
}
});
// 清除
SINGLE_FACTORY.clear();
}
}
public static IOException closeAllQuietly(Iterable<? extends Closeable> iterable) {
if (iterable == null) return null;
LinkedList<IOException> exceptions = null;
for (Closeable closeable : iterable) {
try {
closeable.close();
} catch (IOException x) {
if (exceptions == null) exceptions = new LinkedList<IOException>();
exceptions.add(x);
}
}
IOException ex = MultipleCausesIOException.fromIOExceptions(exceptions);
return ex;
}
public void handle(Message message) throws SequenceFault, RMException {
final AddressingProperties maps = ContextUtils.retrieveMAPs(message, false, false, false);
//if wsrmp:RMAssertion and addressing is optional
if (maps == null && isRMPolicyEnabled(message)) {
return;
}
LOG.entering(getClass().getName(), "handleMessage");
Destination dest = getManager().getDestination(message);
final boolean robust =
MessageUtils.getContextualBoolean(message, Message.ROBUST_ONEWAY, false);
if (robust) {
message.remove(RMMessageConstants.DELIVERING_ROBUST_ONEWAY);
dest.acknowledge(message);
}
dest.processingComplete(message);
// close InputStream of RMCaptureInInterceptor, to delete tmp files in filesystem
Closeable closable = (Closeable)message.get("org.apache.cxf.ws.rm.content.closeable");
if (null != closable) {
try {
closable.close();
} catch (IOException e) {
// Ignore
}
}
}
/**
* 在final中安静的关闭, 不再往外抛出异常避免影响原有异常,最常用函数. 同时兼容Closeable为空未实际创建的情况.
*
* @see {@link Closeables#close}
*/
public static void closeQuietly(Closeable closeable) {
if (closeable == null) {
return;
}
try {
closeable.close();
} catch (IOException e) {
logger.warn(CLOSE_ERROR_MESSAGE, e);
}
}
@Override
public Closeable acquirePermits(long permits)
throws InterruptedException {
int permitsToAcquire = Ints.checkedCast(permits);
this.permitPool.acquire(permitsToAcquire);
return new PoolPermitCloseable(this.permitPool, permitsToAcquire);
}
@Override
public void process(Object outputElem) throws Exception {
try (Closeable scope = context.enterProcess()) {
checkStarted();
mayInitializeWriterInProcess();
byteCount.addValue(writer.add(outputElem));
}
}
protected void closeQuietly(Closeable closable) {
try {
closable.close();
} catch (IOException e) {
// ignore
}
}
public static void close(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
static void test(Class<?> c) {
System.out.println("\nTest " + c);
if (Closeable.class.isAssignableFrom(c)) {
System.out.println("Test passed!");
} else {
error++;
System.out.println("Test failed!");
}
}
public static void closeSilently(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception ignored) {
}
}
}
synchronized void addFileHandle(Closeable c, String name, Handle handle) {
Integer v = openFiles.get(name);
if (v != null) {
v = Integer.valueOf(v.intValue()+1);
openFiles.put(name, v);
} else {
openFiles.put(name, Integer.valueOf(1));
}
openFileHandles.put(c, new RuntimeException("unclosed Index" + handle.name() + ": " + name));
}
private void acquirePermits(int permits, String op) throws IOException {
try {
Closeable closeable = getRateLimiter().acquirePermits(permits);
if (closeable == null) {
throw new NotEnoughPermitsException(op);
}
} catch (InterruptedException e) {
throw new NotEnoughPermitsException(op, e);
}
}
public static void closeCloseable(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} finally {
closeable = null;
}
}
}
private static void closeSafely(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void closeResourceQuietly(@Nullable Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
Log.e(ResourceUtils.class.getName(), e.getMessage(), e);
}
}
}
/**
* Closes this URLClassLoader, so that it can no longer be used to load
* new classes or resources that are defined by this loader.
* Classes and resources defined by any of this loader's parents in the
* delegation hierarchy are still accessible. Also, any classes or resources
* that are already loaded, are still accessible.
* <p>
* In the case of jar: and file: URLs, it also closes any files
* that were opened by it. If another thread is loading a
* class when the {@code close} method is invoked, then the result of
* that load is undefined.
* <p>
* The method makes a best effort attempt to close all opened files,
* by catching {@link IOException}s internally. Unchecked exceptions
* and errors are not caught. Calling close on an already closed
* loader has no effect.
* <p>
* @exception IOException if closing any file opened by this class loader
* resulted in an IOException. Any such exceptions are caught internally.
* If only one is caught, then it is re-thrown. If more than one exception
* is caught, then the second and following exceptions are added
* as suppressed exceptions of the first one caught, which is then re-thrown.
*
* @exception SecurityException if a security manager is set, and it denies
* {@link RuntimePermission}{@code ("closeClassLoader")}
*
* @since 1.7
*/
public void close() throws IOException {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(new RuntimePermission("closeClassLoader"));
}
List<IOException> errors = ucp.closeLoaders();
// now close any remaining streams.
synchronized (closeables) {
Set<Closeable> keys = closeables.keySet();
for (Closeable c : keys) {
try {
c.close();
} catch (IOException ioex) {
errors.add(ioex);
}
}
closeables.clear();
}
if (errors.isEmpty()) {
return;
}
IOException firstex = errors.remove(0);
// Suppress any remaining exceptions
for (IOException error: errors) {
firstex.addSuppressed(error);
}
throw firstex;
}
public static void closeQuietly(Closeable closeable) {
if (closeable == null) return;
try {
closeable.close();
} catch (Throwable ignored) {
}
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
try (Closeable closeable = IMAPMDCContext.from(ctx, attributes)) {
imapCommandsMetric.increment();
ImapSession session = (ImapSession) attributes.get(ctx.getChannel());
ImapResponseComposer response = (ImapResponseComposer) ctx.getAttachment();
ImapMessage message = (ImapMessage) e.getMessage();
ChannelPipeline cp = ctx.getPipeline();
try {
if (cp.get(NettyConstants.EXECUTION_HANDLER) != null) {
cp.addBefore(NettyConstants.EXECUTION_HANDLER, NettyConstants.HEARTBEAT_HANDLER, heartbeatHandler);
} else {
cp.addBefore(NettyConstants.CORE_HANDLER, NettyConstants.HEARTBEAT_HANDLER, heartbeatHandler);
}
final ResponseEncoder responseEncoder = new ResponseEncoder(encoder, response);
processor.process(message, responseEncoder, session);
if (session.getState() == ImapSessionState.LOGOUT) {
// Make sure we close the channel after all the buffers were flushed out
Channel channel = ctx.getChannel();
if (channel.isConnected()) {
channel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
final IOException failure = responseEncoder.getFailure();
if (failure != null) {
LOGGER.info(failure.getMessage());
LOGGER.debug("Failed to write {}", message, failure);
throw failure;
}
} finally {
ctx.getPipeline().remove(NettyConstants.HEARTBEAT_HANDLER);
}
super.messageReceived(ctx, e);
}
}
public static void closeQuietly(/* Auto */Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
}
/**
* 大部分Close关闭流,以及实现Closeable的功能可使用此方法
*
* @param c Closeable对象,包括Stream等
*/
public static void closeQuietly(Closeable c) {
try {
if (c != null) {
c.close();
}
} catch (final IOException ioe) {
// ignore
}
}
private static void suppressedClose(Closeable... closeus) {
for (Closeable closeme : closeus) {
if (closeme != null) {
try {
closeme.close();
} catch (IOException ignored) {
}
}
}
}
private void uncache() {
if (dispatch instanceof Closeable) {
try {
((Closeable)dispatch).close();
} catch (IOException e) {
//ignorable
}
}
dispatch = null;
service = null;
}
private void close(Closeable closeable) throws AtlasException {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
throw new AtlasException(e);
}
}
}
/**
* Convert a Closeable to a Runnable by converting checked IOException
* to UncheckedIOException
*/
private static Runnable asUncheckedRunnable(Closeable c) {
return () -> {
try {
c.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
/**
* Closes this URLClassLoader, so that it can no longer be used to load
* new classes or resources that are defined by this loader.
* Classes and resources defined by any of this loader's parents in the
* delegation hierarchy are still accessible. Also, any classes or resources
* that are already loaded, are still accessible.
* <p>
* In the case of jar: and file: URLs, it also closes any files
* that were opened by it. If another thread is loading a
* class when the {@code close} method is invoked, then the result of
* that load is undefined.
* <p>
* The method makes a best effort attempt to close all opened files,
* by catching {@link IOException}s internally. Unchecked exceptions
* and errors are not caught. Calling close on an already closed
* loader has no effect.
* <p>
* @exception IOException if closing any file opened by this class loader
* resulted in an IOException. Any such exceptions are caught internally.
* If only one is caught, then it is re-thrown. If more than one exception
* is caught, then the second and following exceptions are added
* as suppressed exceptions of the first one caught, which is then re-thrown.
*
* @exception SecurityException if a security manager is set, and it denies
* {@link RuntimePermission}{@code ("closeClassLoader")}
*
* @since 1.7
*/
public void close() throws IOException {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(new RuntimePermission("closeClassLoader"));
}
List<IOException> errors = ucp.closeLoaders();
// now close any remaining streams.
synchronized (closeables) {
Set<Closeable> keys = closeables.keySet();
for (Closeable c : keys) {
try {
c.close();
} catch (IOException ioex) {
errors.add(ioex);
}
}
closeables.clear();
}
if (errors.isEmpty()) {
return;
}
IOException firstex = errors.remove(0);
// Suppress any remaining exceptions
for (IOException error: errors) {
firstex.addSuppressed(error);
}
throw firstex;
}
private static void close(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
// nothing
}
}
}