|
Java example source code file (ByteSource.java)
The ByteSource.java Java example source code
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.ByteStreams.createBuffer;
import static com.google.common.io.ByteStreams.skipUpTo;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.hash.Funnels;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Iterator;
/**
* A readable source of bytes, such as a file. Unlike an {@link InputStream}, a {@code ByteSource}
* is not an open, stateful stream for input that can be read and closed. Instead, it is an
* immutable <i>supplier of {@code InputStream} instances.
*
* <p>{@code ByteSource} provides two kinds of methods:
* <ul>
* <li>Methods that return a stream: These methods should return a new, independent
* instance each time they are called. The caller is responsible for ensuring that the returned
* stream is closed.
* <li>Convenience methods: These are implementations of common operations that are typically
* implemented by opening a stream using one of the methods in the first category, doing
* something and finally closing the stream that was opened.
* </ul>
*
* @since 14.0
* @author Colin Decker
*/
@GwtIncompatible
public abstract class ByteSource {
/**
* Constructor for use by subclasses.
*/
protected ByteSource() {}
/**
* Returns a {@link CharSource} view of this byte source that decodes bytes read from this source
* as characters using the given {@link Charset}.
*
* <p>If {@link CharSource#asByteSource} is called on the returned source with the same charset,
* the default implementation of this method will ensure that the original {@code ByteSource} is
* returned, rather than round-trip encoding. Subclasses that override this method should behave
* the same way.
*/
public CharSource asCharSource(Charset charset) {
return new AsCharSource(charset);
}
/**
* Opens a new {@link InputStream} for reading from this source. This method should return a new,
* independent stream each time it is called.
*
* <p>The caller is responsible for ensuring that the returned stream is closed.
*
* @throws IOException if an I/O error occurs in the process of opening the stream
*/
public abstract InputStream openStream() throws IOException;
/**
* Opens a new buffered {@link InputStream} for reading from this source. The returned stream is
* not required to be a {@link BufferedInputStream} in order to allow implementations to simply
* delegate to {@link #openStream()} when the stream returned by that method does not benefit from
* additional buffering (for example, a {@code ByteArrayInputStream}). This method should return a
* new, independent stream each time it is called.
*
* <p>The caller is responsible for ensuring that the returned stream is closed.
*
* @throws IOException if an I/O error occurs in the process of opening the stream
* @since 15.0 (in 14.0 with return type {@link BufferedInputStream})
*/
public InputStream openBufferedStream() throws IOException {
InputStream in = openStream();
return (in instanceof BufferedInputStream)
? (BufferedInputStream) in
: new BufferedInputStream(in);
}
/**
* Returns a view of a slice of this byte source that is at most {@code length} bytes long
* starting at the given {@code offset}. If {@code offset} is greater than the size of this
* source, the returned source will be empty. If {@code offset + length} is greater than the size
* of this source, the returned source will contain the slice starting at {@code offset} and
* ending at the end of this source.
*
* @throws IllegalArgumentException if {@code offset} or {@code length} is negative
*/
public ByteSource slice(long offset, long length) {
return new SlicedByteSource(offset, length);
}
/**
* Returns whether the source has zero bytes. The default implementation returns true if
* {@link #sizeIfKnown} returns zero, falling back to opening a stream and checking for EOF if the
* size is not known.
*
* <p>Note that, in cases where {@code sizeIfKnown} returns zero, it is possible that bytes
* are actually available for reading. (For example, some special files may return a size of 0
* despite actually having content when read.) This means that a source may return {@code true}
* from {@code isEmpty()} despite having readable content.
*
* @throws IOException if an I/O error occurs
* @since 15.0
*/
public boolean isEmpty() throws IOException {
Optional<Long> sizeIfKnown = sizeIfKnown();
if (sizeIfKnown.isPresent() && sizeIfKnown.get() == 0L) {
return true;
}
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
return in.read() == -1;
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Returns the size of this source in bytes, if the size can be easily determined without actually
* opening the data stream.
*
* <p>The default implementation returns {@link Optional#absent}. Some sources, such as a file,
* may return a non-absent value. Note that in such cases, it is <i>possible that this method
* will return a different number of bytes than would be returned by reading all of the bytes (for
* example, some special files may return a size of 0 despite actually having content when read).
*
* <p>Additionally, for mutable sources such as files, a subsequent read may return a different
* number of bytes if the contents are changed.
*
* @since 19.0
*/
@Beta
public Optional<Long> sizeIfKnown() {
return Optional.absent();
}
/**
* Returns the size of this source in bytes, even if doing so requires opening and traversing an
* entire stream. To avoid a potentially expensive operation, see {@link #sizeIfKnown}.
*
* <p>The default implementation calls {@link #sizeIfKnown} and returns the value if present. If
* absent, it will fall back to a heavyweight operation that will open a stream, read (or
* {@link InputStream#skip(long) skip}, if possible) to the end of the stream and return the total
* number of bytes that were read.
*
* <p>Note that for some sources that implement {@link #sizeIfKnown} to provide a more efficient
* implementation, it is <i>possible that this method will return a different number of bytes
* than would be returned by reading all of the bytes (for example, some special files may return
* a size of 0 despite actually having content when read).
*
* <p>In either case, for mutable sources such as files, a subsequent read may return a different
* number of bytes if the contents are changed.
*
* @throws IOException if an I/O error occurs in the process of reading the size of this source
*/
public long size() throws IOException {
Optional<Long> sizeIfKnown = sizeIfKnown();
if (sizeIfKnown.isPresent()) {
return sizeIfKnown.get();
}
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
return countBySkipping(in);
} catch (IOException e) {
// skip may not be supported... at any rate, try reading
} finally {
closer.close();
}
closer = Closer.create();
try {
InputStream in = closer.register(openStream());
return ByteStreams.exhaust(in);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Counts the bytes in the given input stream using skip if possible. Returns SKIP_FAILED if the
* first call to skip threw, in which case skip may just not be supported.
*/
private long countBySkipping(InputStream in) throws IOException {
long count = 0;
long skipped;
while ((skipped = skipUpTo(in, Integer.MAX_VALUE)) > 0) {
count += skipped;
}
return count;
}
/**
* Copies the contents of this byte source to the given {@code OutputStream}. Does not close
* {@code output}.
*
* @return the number of bytes copied
* @throws IOException if an I/O error occurs in the process of reading from this source or
* writing to {@code output}
*/
@CanIgnoreReturnValue
public long copyTo(OutputStream output) throws IOException {
checkNotNull(output);
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
return ByteStreams.copy(in, output);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Copies the contents of this byte source to the given {@code ByteSink}.
*
* @return the number of bytes copied
* @throws IOException if an I/O error occurs in the process of reading from this source or
* writing to {@code sink}
*/
@CanIgnoreReturnValue
public long copyTo(ByteSink sink) throws IOException {
checkNotNull(sink);
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
OutputStream out = closer.register(sink.openStream());
return ByteStreams.copy(in, out);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Reads the full contents of this byte source as a byte array.
*
* @throws IOException if an I/O error occurs in the process of reading from this source
*/
public byte[] read() throws IOException {
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
return ByteStreams.toByteArray(in);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Reads the contents of this byte source using the given {@code processor} to process bytes as
* they are read. Stops when all bytes have been read or the consumer returns {@code false}.
* Returns the result produced by the processor.
*
* @throws IOException if an I/O error occurs in the process of reading from this source or if
* {@code processor} throws an {@code IOException}
* @since 16.0
*/
@Beta
@CanIgnoreReturnValue // some processors won't return a useful result
public <T> T read(ByteProcessor
Other Java examples (source code examples)Here is a short list of links related to this Java ByteSource.java source code file: |
| ... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.