下面列出了怎么用java.io.InputStream的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public byte[] serialize(String topic, S3ObjectInputStream data) {
InputStream is = data.getDelegateStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] byteArray = new byte[16384];
try {
while ((nRead = is.read(byteArray, 0, byteArray.length)) != -1) {
buffer.write(byteArray, 0, nRead);
}
} catch (IOException e) {
LOG.warn("I/O error while serializing data from or to topic {}: {} | {}", topic, e.getMessage(), e);
}
return buffer.toByteArray();
}
/**
* We do this inefficiently and read it all in here. The target type
* is assumed to be a String.
*
* @param parameterIndex the first parameter is 1, the second is 2, ...
* @param x the java input stream which contains the ASCII parameter value
* @param length the number of bytes in the stream
* @exception SQLException thrown on failure.
*/
public final void setAsciiStream(int parameterIndex, InputStream x, long length)
throws SQLException {
checkAsciiStreamConditions(parameterIndex);
java.io.Reader r = null;
if (x != null)
{
// Use ISO-8859-1 and not US-ASCII as JDBC seems to define
// ASCII as 8 bits. US-ASCII is 7.
try {
r = new java.io.InputStreamReader(x, "ISO-8859-1");
} catch (java.io.UnsupportedEncodingException uee) {
throw new SQLException(uee.getMessage());
}
}
setCharacterStreamInternal(parameterIndex, r, false, length);
}
private static long readFile(FileOutputStream fos, InputStream in,
long filesize) throws IOException {
int foo;
long tempfilesize=filesize;
while (true) {
if (bufs.length < tempfilesize){
foo = bufs.length;
}else {
foo = (int) tempfilesize;
}
foo = in.read(bufs, 0, foo);
if (foo < 0) {
// error
break;
}
fos.write(bufs, 0, foo);
tempfilesize -= foo;
if (tempfilesize == 0L){
break;
}
}
return tempfilesize;
}
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
InputStream in = UserAttribute362ImplTest.class
.getClassLoader().getResourceAsStream(XML_FILE);
ConfigurationHolder cfp = new ConfigurationHolder();
try {
cfp.processPortletDD(in);
pad = cfp.getPad();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
private void dumpINodeDirectorySection(InputStream in) throws IOException {
out.print("<INodeDirectorySection>");
while (true) {
INodeDirectorySection.DirEntry e = INodeDirectorySection.DirEntry
.parseDelimitedFrom(in);
// note that in is a LimitedInputStream
if (e == null) {
break;
}
out.print("<directory>");
o("parent", e.getParent());
for (long id : e.getChildrenList()) {
o("inode", id);
}
for (int refId : e.getRefChildrenList()) {
o("inodereference-index", refId);
}
out.print("</directory>\n");
}
out.print("</INodeDirectorySection>\n");
}
protected KeycloakDeployment resolveDeployment(String keycloakConfigFile) {
try {
InputStream is = null;
if (keycloakConfigFile.startsWith(PROFILE_RESOURCE)) {
try {
is = new URL(keycloakConfigFile).openStream();
} catch (MalformedURLException mfue) {
throw new RuntimeException(mfue);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
} else {
is = FindFile.findFile(keycloakConfigFile);
}
KeycloakDeployment kd = KeycloakDeploymentBuilder.build(is);
return kd;
} catch (RuntimeException e) {
getLogger().debug("Unable to find or parse file " + keycloakConfigFile + " due to " + e.getMessage(), e);
throw e;
}
}
/**
* Fill TABLE_CITIES_TO_WATCH with all the Cities
*/
private synchronized void fillCityDatabase(SQLiteDatabase db) {
long startInsertTime = System.currentTimeMillis();
InputStream inputStream = context.getResources().openRawResource(R.raw.city_list);
try {
FileReader fileReader = new FileReader();
final List<City> cities = fileReader.readCitiesFromFile(inputStream);
addCities(db, cities);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
long endInsertTime = System.currentTimeMillis();
Log.d("debug_info", "Time for insert:" + (endInsertTime - startInsertTime));
}
private static void loadFromPem(KeyStore keyStore, InputStream inputStream) throws IOException, KeyStoreException {
List<PemObject> pemObjects = PemObject.parse(new String(FileCopyUtils.copyToByteArray(inputStream)));
for (PemObject pemObject : pemObjects) {
if (pemObject.isCertificate()) {
X509Certificate cert = pemObject.getCertificate();
String alias = cert.getSubjectX500Principal().getName();
if (logger.isDebugEnabled()) {
logger.debug(String.format("Adding certificate with alias %s", alias));
}
keyStore.setCertificateEntry(alias, cert);
}
}
}
public static byte[] getFileContentByte(InputStream inputStream, long offset, int length)
throws Exception {
if (offset < 0 || length < 0) {
throw new Exception("getFileContent param error");
}
byte[] fileContent = null;
byte[] tempBuf = new byte[length];
inputStream.skip(offset);
int readLen = inputStream.read(tempBuf);
if (readLen < 0) {
fileContent = new byte[0];
return fileContent;
}
if (readLen < length) {
fileContent = new byte[readLen];
System.arraycopy(tempBuf, 0, fileContent, 0, readLen);
} else {
fileContent = tempBuf;
}
return fileContent;
}
@Override
public InputStream getInputStream() throws IOException {
NetInfo data = intAndGetMyData();
AopInputStream inputStream;
if (DEBUG) {
LogX.d(TAG, SUB_TAG, "... ...getInputStream() ");
}
try {
inputStream = new AopInputStream(this.myConnection.getInputStream());
inspectAndInstrumentResponse(data, this.myConnection);
// TODO:
} catch (IOException e) {
// TODO:
throw e;
}
inputStream.setStreamCompleteListener(this);
return inputStream;
}
/**
* @param args The names of the classes to dump
* @throws Exception
*/
public static void main(String... args) throws Exception {
for (String arg : args) {
ClassLoader cl = ClassFileInstaller.class.getClassLoader();
// Convert dotted class name to a path to a class file
String pathName = arg.replace('.', '/').concat(".class");
InputStream is = cl.getResourceAsStream(pathName);
// Create the class file's package directory
Path p = Paths.get(pathName);
Path parent = p.getParent();
if (parent != null) {
Files.createDirectories(parent);
}
// Create the class file
Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING);
}
}
@Override
public Object readValueFrom(ProtocolReader context, Type type, ClassDefinition definition) throws IOException {
InputStream in = context.getInputStream();
byte information = (byte) in.read();
byte mark = getMark(information);
if (mark == NULL_MARK) {
return null;
}
if (mark == FALSE_MARK) {
if (type == AtomicBoolean.class) {
return new AtomicBoolean(false);
}
return false;
} else if (mark == TRUE_MARK) {
if (type == AtomicBoolean.class) {
return new AtomicBoolean(true);
}
return true;
}
String message = StringUtility.format("类型码[{}]没有对应标记码[{}]", type, mark);
throw new CodecConvertionException(message);
}
@Override
public StreamMetrics create(final Path path, final InputStream data) throws IOException {
checkNotNull(path);
checkNotNull(data);
// Ensure path exists for new blob
Path dir = path.getParent();
checkNotNull(dir, "Null parent for path: %s", path);
DirectoryHelper.mkdir(dir);
final MetricsInputStream input = new MetricsInputStream(data);
try {
try (final OutputStream output = Files.newOutputStream(path, StandardOpenOption.CREATE_NEW)) {
ByteStreams.copy(input, output);
}
}
finally {
// FIXME: Revisit closing stream which is passed in as parameter, this should be the responsibility of the caller
data.close();
}
return input.getMetrics();
}
public void testNTriplesFile()
throws Exception
{
RDFParser turtleParser = createRDFParser();
turtleParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE);
turtleParser.setRDFHandler(new RDFHandlerBase() {
public void handleStatement(Statement st)
throws RDFHandlerException {
if (log.isInfoEnabled())
log.info("Statement: " + st);
}
});
// Note: This is a local copy.
InputStream in = BigdataNTriplesParser.class.getResourceAsStream(NTRIPLES_TEST_FILE);
try {
turtleParser.parse(in, NTRIPLES_TEST_URL);
}
catch (RDFParseException e) {
fail("Failed to parse N-Triples test document: " + e.getMessage());
}
finally {
in.close();
}
}
public void testStreamPoolDeadlock () throws Exception {
FileLock fLock = testFo.lock();
OutputStream os = null;
InputStream is = null;
try {
os = testFo.getOutputStream(fLock);
os.close(); os = null;
is = testFo.getInputStream();
is.close(); is = null;
} finally {
if (fLock != null) fLock.releaseLock();
if (os != null) os.close();
if (is != null) is.close();
}
}
private void readAPP14(InputStream is) throws IOException {
String[] app14Info = {"DCTEncodeVersion: ", "APP14Flags0: ", "APP14Flags1: ", "ColorTransform: "};
int expectedLen = 14; // Expected length of this segment is 14.
int length = IOUtils.readUnsignedShortMM(is);
if (length >= expectedLen) {
byte[] data = new byte[length - 2];
IOUtils.readFully(is, data, 0, length - 2);
byte[] buf = ArrayUtils.subArray(data, 0, 5);
if(Arrays.equals(buf, ADOBE_ID.getBytes())) {
for (int i = 0, j = 5; i < 3; i++, j += 2) {
LOGGER.info("{}{}", app14Info[i], StringUtils.shortToHexStringMM(IOUtils.readShortMM(data, j)));
}
LOGGER.debug("{}{}", app14Info[3], (((data[11]&0xff) == 0)? "Unknown (RGB or CMYK)":
((data[11]&0xff) == 1)? "YCbCr":"YCCK" ));
}
}
}
/**
* Loads {@link DownloadRequest DownloadRequests} from the file.
*
* @return The loaded {@link DownloadRequest DownloadRequests}, or an empty array if the file does
* not exist.
* @throws IOException If there is an error reading the file.
*/
public DownloadRequest[] load() throws IOException {
if (!exists()) {
return new DownloadRequest[0];
}
InputStream inputStream = null;
try {
inputStream = atomicFile.openRead();
DataInputStream dataInputStream = new DataInputStream(inputStream);
int version = dataInputStream.readInt();
if (version > VERSION) {
throw new IOException("Unsupported action file version: " + version);
}
int actionCount = dataInputStream.readInt();
ArrayList<DownloadRequest> actions = new ArrayList<>();
for (int i = 0; i < actionCount; i++) {
try {
actions.add(readDownloadRequest(dataInputStream));
} catch (UnsupportedRequestException e) {
// remove DownloadRequest is not supported. Ignore and continue loading rest.
}
}
return actions.toArray(new DownloadRequest[0]);
} finally {
Util.closeQuietly(inputStream);
}
}
public MessageType parseDelimitedFrom(
InputStream input,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
return checkMessageInitialized(
parsePartialDelimitedFrom(input, extensionRegistry));
}
@Test
public void testServiceKeyConfig() {
try {
// TPROXY.TNAME.ID.http://@{TGT_HOST}:@{TGT_PORT}/TPlaceName$5050
InputStream config = new ByteArrayInputStream(configKeyData);
PlaceTest tp = new PlaceTest(config, null, "http://example.com:8001/PlaceTest");
assertEquals("Configured place name", "TPlaceName", tp.getPlaceName());
assertEquals("Primary proxy", "TPROXY", tp.getPrimaryProxy());
assertEquals("Key generation", "TPROXY.TNAME.ID.http://localhost:8001/TPlaceName", tp.getKey());
DirectoryEntry de = tp.getDirectoryEntry();
assertNotNull("Directory entry", de);
assertEquals("Cost in directory entry", 50, de.getCost());
assertEquals("Quality in directory entry", 50, de.getQuality());
assertEquals("Description in directory entry", "test place", de.getDescription());
Set<String> keys = tp.getKeys();
assertNotNull("Keys as a set", keys);
assertEquals("Size of Keys", 1, keys.size());
Set<String> proxies = tp.getProxies();
assertNotNull("Proxies as a set", proxies);
assertEquals("Size of proxies set", 1, proxies.size());
assertTrue("Proxies contains original in set", proxies.contains("TPROXY"));
} catch (IOException iox) {
fail("Place should have configured with SERVICE_KEY: " + iox.getMessage());
}
}
/**
* Compare two files in order to check if they contain the same lines (but maybe not in the same order).
*
* @param expected the file expected to match the actual one
* @param actual the actual file
* @return <code>true</code> if both files contains the same lines, <code>false</code> else.
* @throws IOException in case of reading file problem.
*/
public static boolean doesFilesContainSameLines(@NotNull InputStream expected, @NotNull InputStream actual)
throws IOException {
LineIterator actualLI = IOUtils.lineIterator(actual, StandardCharsets.UTF_8);
LineIterator expectedLI = IOUtils.lineIterator(expected, StandardCharsets.UTF_8);
Map<String, Integer> unmatchedLinesFromActualFile = new HashMap<>();
Map<String, Integer> unmatchedLinesFromExpectedFile = new HashMap<>();
while (actualLI.hasNext() || expectedLI.hasNext()) {
String actualLine = actualLI.hasNext() ? actualLI.nextLine() : null;
String expectedLine = expectedLI.hasNext() ? expectedLI.nextLine() : null;
if (actualLine != null && expectedLine != null) {
if (!actualLine.equals(expectedLine)) {
if (!removeOrDecrement(unmatchedLinesFromExpectedFile, actualLine)) {
putOrIncrement(unmatchedLinesFromActualFile, actualLine);
}
if (!removeOrDecrement(unmatchedLinesFromActualFile, expectedLine)) {
putOrIncrement(unmatchedLinesFromExpectedFile, expectedLine);
}
}
} else if (actualLine != null) {
putOrIncrement(unmatchedLinesFromActualFile, actualLine);
} else {
putOrIncrement(unmatchedLinesFromExpectedFile, expectedLine);
}
}
if (unmatchedLinesFromActualFile.isEmpty() && unmatchedLinesFromExpectedFile.isEmpty()) {
return true;
}
if (!unmatchedLinesFromActualFile.isEmpty()) {
LOGGER.warn("Lines present only in actual file :\n" + getKeys(unmatchedLinesFromActualFile));
}
if (!unmatchedLinesFromExpectedFile.isEmpty()) {
LOGGER.warn("Lines present only in expected file :\n" + getKeys(unmatchedLinesFromExpectedFile));
}
return false;
}
@Override
public InputStream openStream(String url, Map<String, String> headers, int connectTimeout, int readTimeout) throws IOException {
URLConnection connection = openConnection(url, headers, connectTimeout, readTimeout);
if (log.isLoggable(Level.FINE)) {
log.fine(String.format("Using URLConnection for url [%s].", url));
}
return connection.getInputStream();
}
public static void close(InputStream inputStream, OutputStream outputStream, Socket socket,
ServerSocket serverSocket) {
close(inputStream);
close(outputStream);
close(socket);
close(serverSocket);
}
protected ConnectionRequest createConnectionRequest(final DocumentInfo docInfo,
final IOCallback callback, final Object[] response){
return new ConnectionRequest() {
protected void buildRequestBody(OutputStream os) throws IOException {
if(isPost()) {
if(docInfo.getParams() != null){
OutputStreamWriter w = new OutputStreamWriter(os, docInfo.getEncoding());
w.write(docInfo.getParams());
}
}
}
protected void handleIOException(IOException err) {
if(callback == null) {
response[0] = err;
}
super.handleIOException(err);
}
protected boolean shouldAutoCloseResponse() {
return callback != null;
}
protected void readResponse(InputStream input) throws IOException {
if(callback != null) {
callback.streamReady(input, docInfo);
} else {
response[0] = input;
synchronized(LOCK) {
LOCK.notify();
}
}
}
};
}
@Override
public InputStream getInputStream() throws IOException {
BufferedInputStream input = new BufferedInputStream(mWrappedConnection.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int size = 1024;
int len;
int offset = 0;
byte[] buf = new byte[size];
boolean injectedException = false;
try {
while ((len = input.read(buf, 0, size)) != -1) {
if (injector != null) {
injector.injectInputStream(
rangeOffset + offset, rangeOffset + offset + len); // This might throw.
}
bos.write(buf, 0, len);
offset += len;
}
} catch (IOException ignore) {
// Catching injected IOException.
injectedException = true;
}
buf = bos.toByteArray();
mBuilder.append("\ngetInputStream:").append(Base64.encodeToString(buf, Base64.NO_WRAP));
MockInputStreamHelper inputStream = new MockInputStreamHelper(buf);
if (injectedException) {
mBuilder.append(":Exception");
inputStream.injectExceptionAt(offset);
}
return inputStream;
}
public NameVersion parse(final InputStream packageXmlInputStream)
throws ParserConfigurationException, SAXException, IOException {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
final DocumentBuilder builder = factory.newDocumentBuilder();
final NameVersion nameVersion = new NameVersion();
final Document packageXml = builder.parse(packageXmlInputStream);
final Node packageNode = XmlUtil.getNode("package", packageXml);
nameVersion.setName(XmlUtil.getNode("name", packageNode).getTextContent());
final Node versionNode = XmlUtil.getNode("version", packageNode);
nameVersion.setVersion(XmlUtil.getNode("release", versionNode).getTextContent());
return nameVersion;
}
@Override
@SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
public void deserializeBody(InputStream stream, TLContext context) throws IOException {
flags = readInt(stream);
ipv6 = (flags & 1) != 0;
mediaOnly = (flags & 2) != 0;
tcpoOnly = (flags & 4) != 0;
cdn = (flags & 8) != 0;
id = readInt(stream);
ipAddress = readTLString(stream);
port = readInt(stream);
}
/**
* @return a mutable list
* @throws IOException
*/
public static List<SourceFile> getDefaultExterns() throws IOException {
InputStream input = CommandLineRunner.class.getResourceAsStream(
"/externs.zip");
if (input == null) {
// In some environments, the externs.zip is relative to this class.
input = CommandLineRunner.class.getResourceAsStream("externs.zip");
}
Preconditions.checkNotNull(input);
ZipInputStream zip = new ZipInputStream(input);
Map<String, SourceFile> externsMap = Maps.newHashMap();
for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) {
BufferedInputStream entryStream = new BufferedInputStream(
new LimitInputStream(zip, entry.getSize()));
externsMap.put(entry.getName(),
SourceFile.fromInputStream(
// Give the files an odd prefix, so that they do not conflict
// with the user's files.
"externs.zip//" + entry.getName(),
entryStream));
}
Preconditions.checkState(
externsMap.keySet().equals(Sets.newHashSet(DEFAULT_EXTERNS_NAMES)),
"Externs zip must match our hard-coded list of externs.");
// Order matters, so the resources must be added to the result list
// in the expected order.
List<SourceFile> externs = Lists.newArrayList();
for (String key : DEFAULT_EXTERNS_NAMES) {
externs.add(externsMap.get(key));
}
return externs;
}
/**
* Creates a new TrueType font for embedding.
*/
private PDTrueTypeFont(PDDocument document, InputStream ttfStream, Encoding encoding)
throws IOException
{
PDTrueTypeFontEmbedder embedder = new PDTrueTypeFontEmbedder(document, dict, ttfStream,
encoding);
this.encoding = encoding;
ttf = embedder.getTrueTypeFont();
setFontDescriptor(embedder.getFontDescriptor());
isEmbedded = true;
isDamaged = false;
glyphList = GlyphList.getAdobeGlyphList();
}
private static void runThreadDump(String pid, String args[]) throws Exception {
VirtualMachine vm = null;
try {
vm = VirtualMachine.attach(pid);
} catch (Exception x) {
String msg = x.getMessage();
if (msg != null) {
System.err.println(pid + ": " + msg);
} else {
x.printStackTrace();
}
if ((x instanceof AttachNotSupportedException) &&
(loadSAClass() != null)) {
System.err.println("The -F option can be used when the target " +
"process is not responding");
}
System.exit(1);
}
// Cast to HotSpotVirtualMachine as this is implementation specific
// method.
InputStream in = ((HotSpotVirtualMachine)vm).remoteDataDump((Object[])args);
// read to EOF and just print output
byte b[] = new byte[256];
int n;
do {
n = in.read(b);
if (n > 0) {
String s = new String(b, 0, n, "UTF-8");
System.out.print(s);
}
} while (n > 0);
in.close();
vm.detach();
}
@Override
public InputStream stream(T value) {
InputStream is = delegate.stream(value);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
lastOutSize = (int) ByteStreams.copy(is, baos);
} catch (IOException e) {
throw new RuntimeException(e);
}
return new ByteArrayInputStream(baos.toByteArray());
}