类java.io.Closeable源码实例Demo

下面列出了怎么用java.io.Closeable的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: RapidFloatingActionButton   文件: RFABIOUtil.java
/**
 * 关闭流
 *
 * @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);
        }
    }
}
 
源代码2 项目: Chronicle-Map   文件: CHMUseCasesTest.java
@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();
    }
}
 
源代码3 项目: cxf   文件: Client.java
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);
    }
 
源代码4 项目: sis   文件: ChannelDataOutputTest.java
/**
 * 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));
}
 
源代码5 项目: simple-robot-core   文件: DependCenter.java
@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();
    }
}
 
源代码6 项目: phoenix   文件: Closeables.java
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;
}
 
源代码7 项目: cxf   文件: RMDeliveryInterceptor.java
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
        }
    }
}
 
源代码8 项目: vjtools   文件: IOUtil.java
/**
 * 在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);
	}
}
 
源代码9 项目: incubator-gobblin   文件: PoolBasedLimiter.java
@Override
public Closeable acquirePermits(long permits)
    throws InterruptedException {
  int permitsToAcquire = Ints.checkedCast(permits);
  this.permitPool.acquire(permitsToAcquire);
  return new PoolPermitCloseable(this.permitPool, permitsToAcquire);
}
 
源代码10 项目: beam   文件: WriteOperation.java
@Override
public void process(Object outputElem) throws Exception {
  try (Closeable scope = context.enterProcess()) {
    checkStarted();
    mayInitializeWriterInProcess();
    byteCount.addValue(writer.add(outputElem));
  }
}
 
源代码11 项目: TakinRPC   文件: GatewayThread.java
protected void closeQuietly(Closeable closable) {
    try {
        closable.close();
    } catch (IOException e) {
        // ignore
    }
}
 
源代码12 项目: android-art-res   文件: MyUtils.java
public static void close(Closeable closeable) {
    try {
        if (closeable != null) {
            closeable.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
源代码13 项目: openjdk-8   文件: CloseableTest.java
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!");
    }
}
 
源代码14 项目: base-imageloader   文件: IoUtils.java
public static void closeSilently(Closeable closeable) {
	if (closeable != null) {
		try {
			closeable.close();
		} catch (Exception ignored) {
		}
	}
}
 
源代码15 项目: lucene-solr   文件: MockDirectoryWrapper.java
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));
}
 
源代码16 项目: incubator-gobblin   文件: ThrottledFileSystem.java
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);
  }
}
 
源代码17 项目: apollo-DuerOS   文件: CarlifeUtil.java
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;
        }
    }
}
 
源代码18 项目: VirtualAPK   文件: ProcessDataBinding.java
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);
        }
    }
}
 
源代码20 项目: openjdk-jdk8u   文件: URLClassLoader.java
/**
* 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;
}
 
源代码21 项目: SimpleCropView   文件: Utils.java
public static void closeQuietly(Closeable closeable) {
  if (closeable == null) return;
  try {
    closeable.close();
  } catch (Throwable ignored) {
  }
}
 
源代码22 项目: james-project   文件: ImapChannelUpstreamHandler.java
@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);
    }
}
 
源代码23 项目: mimi-reader   文件: Utils.java
public static void closeQuietly(/* Auto */Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (RuntimeException rethrown) {
            throw rethrown;
        } catch (Exception ignored) {
        }
    }
}
 
源代码24 项目: springreplugin   文件: CloseableUtils.java
/**
 * 大部分Close关闭流,以及实现Closeable的功能可使用此方法
 *
 * @param c Closeable对象,包括Stream等
 */
public static void closeQuietly(Closeable c) {
    try {
        if (c != null) {
            c.close();
        }
    } catch (final IOException ioe) {
        // ignore
    }
}
 
源代码25 项目: mycore   文件: MCREpubZipResource.java
private static void suppressedClose(Closeable... closeus) {
    for (Closeable closeme : closeus) {
        if (closeme != null) {
            try {
                closeme.close();
            } catch (IOException ignored) {
            }
        }
    }
}
 
源代码26 项目: cxf   文件: WSDiscoveryClient.java
private void uncache() {
    if (dispatch instanceof Closeable) {
        try {
            ((Closeable)dispatch).close();
        } catch (IOException e) {
            //ignorable
        }
    }
    dispatch = null;
    service = null;
}
 
源代码27 项目: atlas   文件: HBaseBasedAuditRepository.java
private void close(Closeable closeable) throws AtlasException {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException e) {
            throw new AtlasException(e);
        }
    }
}
 
源代码28 项目: Java8CN   文件: Files.java
/**
 * 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);
        }
    };
}
 
源代码29 项目: jdk8u-jdk   文件: URLClassLoader.java
/**
* 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;
}
 
源代码30 项目: Xpatch   文件: ShellCmdUtil.java
private static void close(Closeable stream) {
    if (stream != null) {
        try {
            stream.close();
        } catch (Exception e) {
            // nothing
        }
    }
}
 
 类所在包
 同包方法