下面列出了java.io.InputStream#reset ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* parse the given inputSource with a new Parser
* @param inputSource
* @return the document parsed from the input Source
*/
public static Document parse(InputSource inputSource) throws SAXException,IOException {
DocumentBuilder db=newParser();
try {
Document doc=db.parse(inputSource);
return doc;
} catch (java.net.MalformedURLException mue) {
if (EXCEPTION_DEBUG) {
String msg=mue.getMessage();
if (msg!=null) {
System.err.println(msg);
}
InputStream is=inputSource.getByteStream();
is.reset();
String content=parseISToString(is);
System.err.println(content);
}
throw mue;
}
}
/**
* Tests that shifting of existing bytes works.
*
* @throws IOException if something goes wrong
*/
public void testMarkResetShiftBytesFew_Internal()
throws IOException {
InputStream is = getStream(128*1024);
byte[] buf = new byte[DEFAULT_INTERNAL_BUFFER_SIZE - 2*1024];
fillArray(is, buf);
// The following mark fits within the existing default buffer, but the
// bytes after the mark have to be shifted to the left.
is.mark(4*1024);
byte[] readBeforeReset = new byte[3*1024];
byte[] readAfterReset = new byte[3*1024];
fillArray(is, readBeforeReset);
// Obtain something to compare with.
InputStream src = getStream(128*1024);
InputStreamUtil.skipFully(src, DEFAULT_INTERNAL_BUFFER_SIZE - 2*1024);
byte[] comparisonRead = new byte[3*1024];
fillArray(src, comparisonRead);
// Compare
assertEquals(new ByteArrayInputStream(comparisonRead),
new ByteArrayInputStream(readBeforeReset));
// Reset the stream.
is.reset();
fillArray(is, readAfterReset);
assertEquals(new ByteArrayInputStream(readBeforeReset),
new ByteArrayInputStream(readAfterReset));
}
@Override
public void setSource(String fileName, final InputStream src) {
if (src != null) {
resource = new StreamResource((StreamResource.StreamSource) () -> {
try {
src.reset();
} catch (IOException e) {
Logger log = LoggerFactory.getLogger(WebEmbedded.this.getClass());
log.debug("Ignored IOException on stream reset", e);
}
return src;
}, fileName);
component.setSource(resource);
} else {
resetSource();
}
}
/**
* Tests that the reset-call will fail we exceed the mark ahead limit and
* the internal buffer has to be refilled.
*
* @throws IOException if something goes wrong
*/
public void testMarkResetExceedReadAheadLimitFail_Internal()
throws IOException {
InputStream is = getStream(64*1024+17);
is.mark(10);
// The internal buffer is 32 KB (implementation detail).
int toRead = 38*1024+7;
int read = 0;
byte[] buf = new byte[toRead];
while (read < toRead) {
read += is.read(buf, read, toRead - read);
}
// Note the following is implementation dependent.
try {
is.reset();
fail("reset-call was expected to throw IOException");
} catch (IOException ioe) {
// As expected, do nothing
}
}
long getBlobSize(final long blobHandle) throws IOException {
final LongHashMap<InputStream> blobStreams = this.blobStreams;
if (blobStreams != null) {
final InputStream stream = blobStreams.get(blobHandle);
if (stream != null) {
stream.reset();
return stream.skip(Long.MAX_VALUE); // warning, this may return inaccurate results
}
}
final LongHashMap<File> blobFiles = this.blobFiles;
if (blobFiles != null) {
final File file = blobFiles.get(blobHandle);
if (file != null) {
return file.length();
}
}
return -1;
}
public static String markRead(InputStream a, int x, int y) throws IOException {
int m = 0;
int r;
StringBuilder builder = new StringBuilder();
do {
m++;
r = a.read();
if (m == x)
a.mark((x + y));
if (m == (x + y))
a.reset();
if (r != -1)
builder.append((char) r);
} while (r != -1);
return builder.toString();
}
public void testNewInput_skip() throws IOException {
InputStream input = stringUnderTest.newInput();
int stringSize = stringUnderTest.size();
int nearEndIndex = stringSize * 2 / 3;
long skipped1 = input.skip(nearEndIndex);
assertEquals("InputStream.skip()", skipped1, nearEndIndex);
assertEquals("InputStream.available()",
stringSize - skipped1, input.available());
assertTrue("InputStream.mark() is available", input.markSupported());
input.mark(0);
assertEquals("InputStream.skip(), read()",
stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
assertEquals("InputStream.available()",
stringSize - skipped1 - 1, input.available());
long skipped2 = input.skip(stringSize);
assertEquals("InputStream.skip() incomplete",
skipped2, stringSize - skipped1 - 1);
assertEquals("InputStream.skip(), no more input", 0, input.available());
assertEquals("InputStream.skip(), no more input", -1, input.read());
input.reset();
assertEquals("InputStream.reset() succeded",
stringSize - skipped1, input.available());
assertEquals("InputStream.reset(), read()",
stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
}
/**
* 方法描述:对请求内容进行hash并转为16进制
* @param request
* @return
* @author lixuenan3
* @date 2018年3月22日 下午5:43:31
*/
protected String calculateContentHash(SdkHttpFullRequest.Builder request) {
InputStream payloadStream = getBinaryRequestPayloadStream(request.getContent());
String contentSha256 = BinaryUtils.toHex(hash(payloadStream));
try {
payloadStream.reset();
} catch (IOException e) {
throw new SdkClientException("Unable to reset stream after calculating signature", e);
}
return contentSha256;
}
/**
* Indicates whether the response has an empty message body.
* <p>Implementation tries to read the first bytes of the response stream:
* <ul>
* <li>if no bytes are available, the message body is empty</li>
* <li>otherwise it is not empty and the stream is reset to its start for further reading</li>
* </ul>
* @return {@code true} if the response has a zero-length message body, {@code false} otherwise
* @throws IOException in case of I/O errors
*/
@SuppressWarnings("ConstantConditions")
public boolean hasEmptyMessageBody() throws IOException {
InputStream body = this.response.getBody();
// Per contract body shouldn't be null, but check anyway..
if (body == null) {
return true;
}
if (body.markSupported()) {
body.mark(1);
if (body.read() == -1) {
return true;
}
else {
body.reset();
return false;
}
}
else {
this.pushbackInputStream = new PushbackInputStream(body);
int b = this.pushbackInputStream.read();
if (b == -1) {
return true;
}
else {
this.pushbackInputStream.unread(b);
return false;
}
}
}
public AudioFileFormat getAudioFileFormat(InputStream stream)
throws UnsupportedAudioFileException, IOException {
stream.mark(200);
AudioFileFormat format;
try {
format = internal_getAudioFileFormat(stream);
} finally {
stream.reset();
}
return format;
}
public static boolean isID3v1StartPosition(InputStream input) throws IOException {
input.mark(3);
try {
return input.read() == 'T' && input.read() == 'A' && input.read() == 'G';
} finally {
input.reset();
}
}
public static boolean isID3v1StartPosition(InputStream input) throws IOException {
input.mark(3);
try {
return input.read() == 'T' && input.read() == 'A' && input.read() == 'G';
} finally {
input.reset();
}
}
public AudioFileFormat getAudioFileFormat(InputStream stream)
throws UnsupportedAudioFileException, IOException {
stream.mark(200);
AudioFileFormat format;
try {
format = internal_getAudioFileFormat(stream);
} finally {
stream.reset();
}
return format;
}
public static DexBackedOdexFile fromInputStream(@Nonnull Opcodes opcodes,
@Nonnull InputStream is) throws IOException {
if (!is.markSupported()) {
throw new IllegalArgumentException("InputStream must support mark");
}
is.mark(8);
byte[] partialHeader = new byte[8];
try {
ByteStreams.readFully(is, partialHeader);
} catch (EOFException ex) {
throw new NotADexFile("File is too short");
} finally {
is.reset();
}
verifyMagic(partialHeader);
is.reset();
byte[] odexBuf = new byte[OdexHeaderItem.ITEM_SIZE];
ByteStreams.readFully(is, odexBuf);
int dexOffset = OdexHeaderItem.getDexOffset(odexBuf);
if (dexOffset > OdexHeaderItem.ITEM_SIZE) {
ByteStreams.skipFully(is, dexOffset - OdexHeaderItem.ITEM_SIZE);
}
byte[] dexBuf = ByteStreams.toByteArray(is);
return new DexBackedOdexFile(opcodes, odexBuf, dexBuf);
}
public Soundbank getSoundbank(InputStream stream)
throws InvalidMidiDataException, IOException {
try {
stream.mark(512);
return new DLSSoundbank(stream);
} catch (RIFFInvalidFormatException e) {
stream.reset();
return null;
}
}
public AudioFileFormat getAudioFileFormat(InputStream stream)
throws UnsupportedAudioFileException, IOException {
stream.mark(200);
AudioFileFormat format;
try {
format = internal_getAudioFileFormat(stream);
} finally {
stream.reset();
}
return format;
}
public static void main(String[] args) throws Exception {
try
{
setUp();
for (int i = 0; i < 8; i++) {
ModelByteBuffer buff;
if(i % 2 == 0)
buff = new ModelByteBuffer(test_file);
else
buff = new ModelByteBuffer(test_byte_array);
if((i / 2) == 1)
buff.subbuffer(5);
if((i / 2) == 2)
buff.subbuffer(5,500);
if((i / 2) == 3)
buff.subbuffer(5,600,true);
long capacity = buff.capacity();
InputStream is = buff.getInputStream();
try
{
is.mark(1000);
int ret = is.available();
int a = is.read();
is.skip(75);
is.reset();
if(is.available() != ret)
throw new RuntimeException(
"is.available() returns incorrect value ("
+ is.available() + "!="+(ret)+") !");
int b = is.read();
if(a != b)
throw new RuntimeException(
"is doesn't return same value after reset ("
+ a + "!="+b+") !");
is.skip(15);
ret = is.available();
is.mark(1000);
is.reset();
if(is.available() != ret)
throw new RuntimeException(
"is.available() returns incorrect value ("
+ is.available() + "!="+(ret)+") !");
}
finally
{
is.close();
}
if(buff.capacity() != capacity)
throw new RuntimeException("Capacity variable should not change!");
}
}
finally
{
tearDown();
}
}
protected final byte[] streamToBytes(InputStream in, boolean escape, int streamLength, boolean useLength) {
in.mark(Integer.MAX_VALUE); // we may need to read this same stream several times, so we need to reset it at the end.
try {
if (this.streamConvertBuf == null) {
this.streamConvertBuf = new byte[4096];
}
if (streamLength == -1) {
useLength = false;
}
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
int bc = useLength ? readblock(in, this.streamConvertBuf, streamLength) : readblock(in, this.streamConvertBuf);
int lengthLeftToRead = streamLength - bc;
if (escape) {
bytesOut.write('_');
bytesOut.write('b');
bytesOut.write('i');
bytesOut.write('n');
bytesOut.write('a');
bytesOut.write('r');
bytesOut.write('y');
bytesOut.write('\'');
}
while (bc > 0) {
if (escape) {
StringUtils.escapeblockFast(this.streamConvertBuf, bytesOut, bc, this.usingAnsiMode);
} else {
bytesOut.write(this.streamConvertBuf, 0, bc);
}
if (useLength) {
bc = readblock(in, this.streamConvertBuf, lengthLeftToRead);
if (bc > 0) {
lengthLeftToRead -= bc;
}
} else {
bc = readblock(in, this.streamConvertBuf);
}
}
if (escape) {
bytesOut.write('\'');
}
return bytesOut.toByteArray();
} finally {
try {
in.reset();
} catch (IOException e) {
}
if (this.autoClosePStmtStreams.getValue()) {
try {
in.close();
} catch (IOException ioEx) {
}
in = null;
}
}
}
/**
* Obtains the audio file format of the input stream provided. The stream must
* point to valid audio file data. In general, audio file providers may
* need to read some data from the stream before determining whether they
* support it. These parsers must
* be able to mark the stream, read enough data to determine whether they
* support the stream, and, if not, reset the stream's read pointer to its original
* position. If the input stream does not support this, this method may fail
* with an IOException.
* @param stream the input stream from which file format information should be
* extracted
* @return an <code>AudioFileFormat</code> object describing the audio file format
* @throws UnsupportedAudioFileException if the stream does not point to valid audio
* file data recognized by the system
* @throws IOException if an I/O exception occurs
* @see InputStream#markSupported
* @see InputStream#mark
*/
public AudioFileFormat getAudioFileFormat(InputStream stream) throws UnsupportedAudioFileException, IOException {
// fix for 4489272: AudioSystem.getAudioFileFormat() fails for InputStream, but works for URL
AudioFileFormat aff = getFMT(stream, true);
// the following is not strictly necessary - but was implemented like that in 1.3.0 - 1.4.1
// so I leave it as it was. May remove this for 1.5.0
stream.reset();
return aff;
}
/**
* Obtains the audio file format of the input stream provided. The stream must
* point to valid audio file data. In general, audio file providers may
* need to read some data from the stream before determining whether they
* support it. These parsers must
* be able to mark the stream, read enough data to determine whether they
* support the stream, and, if not, reset the stream's read pointer to its original
* position. If the input stream does not support this, this method may fail
* with an IOException.
* @param stream the input stream from which file format information should be
* extracted
* @return an <code>AudioFileFormat</code> object describing the audio file format
* @throws UnsupportedAudioFileException if the stream does not point to valid audio
* file data recognized by the system
* @throws IOException if an I/O exception occurs
* @see InputStream#markSupported
* @see InputStream#mark
*/
public AudioFileFormat getAudioFileFormat(InputStream stream) throws UnsupportedAudioFileException, IOException {
// fix for 4489272: AudioSystem.getAudioFileFormat() fails for InputStream, but works for URL
AudioFileFormat aff = getFMT(stream, true);
// the following is not strictly necessary - but was implemented like that in 1.3.0 - 1.4.1
// so I leave it as it was. May remove this for 1.5.0
stream.reset();
return aff;
}