下面列出了怎么用java.io.EOFException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* {@inheritDoc}
*
* @see java.nio.channels.SeekableByteChannel#position(long)
*/
@Override
public SeekableByteChannel position(final long newPosition) throws IOException {
// if data hasn't been read in, we'll have to do it below and see if it's available
if (this.endofchannel && (newPosition > this.estimatedLength)) {
throw new EOFException("Position is beyond EOF");
}
long tgtPosition = newPosition - this.minposition;
// see if we can move there
if (tgtPosition < 0) {
throw new IllegalStateException("Cannot move to " + newPosition + " in the stream. Minimum position is " + this.minposition);
}
while (!setOffset(tgtPosition) && !this.endofchannel) {
realignBuffers();
tgtPosition = newPosition - this.minposition;
}
if (newPosition > this.estimatedLength) {
throw new EOFException("Position is beyond EOF");
}
return this;
}
private static DateColumn readLocalDateColumn(String fileName, ColumnMetadata metadata)
throws IOException {
DateColumn dates = DateColumn.create(metadata.getName());
try (FileInputStream fis = new FileInputStream(fileName);
SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
DataInputStream dis = new DataInputStream(sis)) {
boolean EOF = false;
while (!EOF) {
try {
int cell = dis.readInt();
dates.appendInternal(cell);
} catch (EOFException e) {
EOF = true;
}
}
}
return dates;
}
public int write( ByteBuffer src ) throws IOException {
if( !isHandShakeComplete() ) {
processHandshake();
return 0;
}
// assert ( bufferallocations > 1 ); //see #190
//if( bufferallocations <= 1 ) {
// createBuffers( sslEngine.getSession() );
//}
int num = socketChannel.write( wrap( src ) );
if (writeEngineResult.getStatus() == SSLEngineResult.Status.CLOSED) {
throw new EOFException("Connection is closed");
}
return num;
}
/**
* Returns the ASCII characters up to but not including the next "\r\n", or
* "\n".
*
* @throws java.io.EOFException if the stream is exhausted before the next newline
* character.
*/
public static String readAsciiLine(InputStream in) throws IOException {
// TODO: support UTF-8 here instead
StringBuilder result = new StringBuilder(80);
while (true) {
int c = in.read();
if (c == -1) {
throw new EOFException();
} else if (c == '\n') {
break;
}
result.append((char) c);
}
int length = result.length();
if (length > 0 && result.charAt(length - 1) == '\r') {
result.setLength(length - 1);
}
return result.toString();
}
/**
* Close the input stream. Note that we need to read to the end of the
* stream to validate the checksum.
*/
@Override
public void close() throws IOException {
if (curReadahead != null) {
curReadahead.cancel();
}
if (currentOffset < dataLength) {
byte[] t = new byte[Math.min((int)
(Integer.MAX_VALUE & (dataLength - currentOffset)), 32 * 1024)];
while (currentOffset < dataLength) {
int n = read(t, 0, t.length);
if (0 == n) {
throw new EOFException("Could not validate checksum");
}
}
}
in.close();
}
/**
* Reads an eight byte signed <code>int</code> from the underlying input
* stream in little endian order, low byte first.
*
* @return the <code>int</code> read.
* @exception EOFException if the end of the underlying input stream has
* been reached
* @exception IOException if the underlying stream throws an IOException.
*/
public long readLittleEndianLong() throws IOException {
long byte1 = in.read();
long byte2 = in.read();
long byte3 = in.read();
long byte4 = in.read();
long byte5 = in.read();
long byte6 = in.read();
long byte7 = in.read();
long byte8 = in.read();
if (byte8 == -1) {
throw new EOFException();
}
return (byte8 << 56) + (byte7 << 48) + (byte6 << 40) + (byte5 << 32)
+ (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1;
}
private String fileToString(final File file) throws IOException {
final long size = file.length();
if (size > Integer.MAX_VALUE) {
throw new IOException("Can't read a file larger than Integer.MAX_VALUE");
}
final byte[] data = new byte[(int) size];
final FileInputStream in = new FileInputStream(file);
try {
int bytesRead = 0;
while (bytesRead < size) {
int read = in.read(data, bytesRead, (int) size - bytesRead);
if (read == -1) {
throw new EOFException();
}
bytesRead += read;
}
return new String(data);
} finally {
in.close();
}
}
public void readFully(byte[] b, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > b.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > b.length!");
}
while (len > 0) {
int nbytes = read(b, off, len);
if (nbytes == -1) {
throw new EOFException();
}
off += nbytes;
len -= nbytes;
}
}
public static DexBackedDexFile fromInputStream(@Nonnull Opcodes opcodes, @Nonnull InputStream is)
throws IOException {
if (!is.markSupported()) {
throw new IllegalArgumentException("InputStream must support mark");
}
is.mark(44);
byte[] partialHeader = new byte[44];
try {
ByteStreams.readFully(is, partialHeader);
} catch (EOFException ex) {
throw new NotADexFile("File is too short");
} finally {
is.reset();
}
verifyMagicAndByteOrder(partialHeader, 0);
byte[] buf = ByteStreams.toByteArray(is);
return new DexBackedDexFile(opcodes, buf, 0, false);
}
/**
* check whether we have already successfully obtained the key. It also
* initializes the valueInputStream.
*/
void checkKey() throws IOException {
if (klen >= 0) return;
if (atEnd()) {
throw new EOFException("No key-value to read");
}
klen = -1;
vlen = -1;
valueChecked = false;
klen = Utils.readVInt(blkReader);
blkReader.readFully(keyBuffer, 0, klen);
valueBufferInputStream.reset(blkReader);
if (valueBufferInputStream.isLastChunk()) {
vlen = valueBufferInputStream.getRemain();
}
}
/**
* Read objects from the serialized stream, validated with the filter.
*
* @param bytes a byte array to read objects from
* @param filter the ObjectInputFilter
* @return the object deserialized if any
* @throws IOException can be thrown
*/
static Object validate(byte[] bytes,
ObjectInputFilter filter) throws IOException {
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
Object o = ois.readObject();
return o;
} catch (EOFException eof) {
// normal completion
} catch (ClassNotFoundException cnf) {
Assert.fail("Deserializing", cnf);
}
return null;
}
private Long getFirstEntryTime(final File provenanceLogFile) {
if (provenanceLogFile == null) {
return null;
}
try (final RecordReader reader = RecordReaders.newRecordReader(provenanceLogFile, null, Integer.MAX_VALUE)) {
final StandardProvenanceEventRecord firstRecord = reader.nextRecord();
if (firstRecord == null) {
return provenanceLogFile.lastModified();
}
return firstRecord.getEventTime();
} catch (final FileNotFoundException | EOFException fnf) {
return null; // file no longer exists or there's no record in this file
} catch (final IOException ioe) {
logger.warn("Failed to read first entry in file {} due to {}", provenanceLogFile, ioe.toString());
logger.warn("", ioe);
return null;
}
}
protected final int peek(OctetBufferListener octetBufferListener) throws IOException {
if (_octetBufferOffset < _octetBufferEnd) {
return _octetBuffer[_octetBufferOffset] & 0xFF;
} else {
if (octetBufferListener != null) {
octetBufferListener.onBeforeOctetBufferOverwrite();
}
_octetBufferEnd = _s.read(_octetBuffer);
if (_octetBufferEnd < 0) {
throw new EOFException(CommonResourceBundle.getInstance().getString("message.EOF"));
}
_octetBufferOffset = 0;
return _octetBuffer[0] & 0xFF;
}
}
/**
* Reads <code>byteCount</code> bytes of data from the given InputStream, writing to the provided byte array.
*
* @param source the InputStream to read from
* @param destination the destination for the data
* @param byteCount the number of bytes to copy
*
* @throws IllegalArgumentException if the given byte array is smaller than <code>byteCount</code> elements.
* @throws EOFException if the InputStream does not have <code>byteCount</code> bytes in the InputStream
* @throws IOException if unable to read from the InputStream
*/
public static void read(final InputStream source, final byte[] destination, final int byteCount) throws IOException {
if (destination.length < byteCount) {
throw new IllegalArgumentException();
}
int bytesRead = 0;
int len;
while (bytesRead < byteCount) {
len = source.read(destination, bytesRead, byteCount - bytesRead);
if (len < 0) {
throw new EOFException("Expected to consume " + byteCount + " bytes but consumed only " + bytesRead);
}
bytesRead += len;
}
}
/**
* Creates a new VarInt from a byte array in little-endian format
*
* @param buf
* Byte array
* @param offset
* Starting offset into the array
* @throws EOFException
* Buffer is too small
*/
public VarInt(byte[] buf, int offset) throws EOFException {
if (offset > buf.length)
throw new EOFException("End-of-data while processing VarInt");
int first = 0x00FF & (int) buf[offset];
if (first < 253) {
// 8 bits.
value = first;
encodedSize = 1;
} else if (first == 253) {
// 16 bits.
if (offset + 2 > buf.length)
throw new EOFException("End-of-data while processing VarInt");
value = (0x00FF & (int) buf[offset + 1]) | ((0x00FF & (int) buf[offset + 2]) << 8);
encodedSize = 3;
} else if (first == 254) {
// 32 bits.
if (offset + 5 > buf.length)
throw new EOFException("End-of-data while processing VarInt");
value = Helper.readUint32LE(buf, offset + 1);
encodedSize = 5;
} else {
// 64 bits.
if (offset + 9 > buf.length)
throw new EOFException("End-of-data while processing VarInt");
value = Helper.readUint64LE(buf, offset + 1);
encodedSize = 9;
}
}
private static TXT decodeTXT(byte[] data) throws IOException {
TXT txt = new TXT();
txt.dict = new HashMap<>();
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
while (true) {
int length;
try {
length = dis.readUnsignedByte();
} catch (EOFException e) {
return txt;
}
byte[] segmentBytes = new byte[length];
dis.readFully(segmentBytes);
String segment = new String(segmentBytes);
int pos = segment.indexOf('=');
String key, value = null;
if (pos != -1) {
key = segment.substring(0, pos);
value = segment.substring(pos + 1);
} else {
key = segment;
}
if (DEBUG) System.out.println(key + "=" + value);
if (!txt.dict.containsKey(key)) {
// from RFC6763
// If a client receives a TXT record containing the same key more than once, then
// the client MUST silently ignore all but the first occurrence of that attribute."
txt.dict.put(key, value);
}
}
}
private Reader getReader(String wal) throws IOException {
Path path = new Path(rs.getWALRootDir(), wal);
long length = rs.getWALFileSystem().getFileStatus(path).getLen();
try {
RecoverLeaseFSUtils.recoverFileLease(fs, path, conf);
return WALFactory.createReader(rs.getWALFileSystem(), path, rs.getConfiguration());
} catch (EOFException e) {
if (length <= 0) {
LOG.warn("File is empty. Could not open {} for reading because {}", path, e);
return null;
}
throw e;
}
}
protected static void checkValidInputFile(FileSystem fs, Path path)
throws IOException
{
//check non-existing file
if( !fs.exists(path) )
throw new IOException("File "+path.toString()+" does not exist on HDFS/LFS.");
//check for empty file
if( HDFSTool.isFileEmpty(fs, path) )
throw new EOFException("Empty input file "+ path.toString() +".");
}
/**
* Get next character
* @return Return the next character
* @throws MifParseException
* @throws EOFException
*/
final public char getChar() throws MifParseException, EOFException {
if (sos >= eos) {
throw new EOFException(Messages.getString("mif.Mif2Xliff.fileEndError"));
}
char n = doc[sos++];
if (n < 0)
throw new MifParseException(Messages.getString("mif.Mif2Xliff.characterError") + formatLineNumber());
return n;
}
public final void setLimit(int length) throws IOException {
start = position;
end = position + length;
if (end > pageData.length) {
start = end = position = 0;
throw new EOFException();
}
}
@Override
public long open(DataSpec dataSpec) throws EncryptedFileDataSourceException {
try {
this.dataSpec = dataSpec;
uri = dataSpec.uri;
File path = new File(dataSpec.uri.getPath());
String name = path.getName();
File keyPath = new File(FileLoader.getInternalCacheDir(), name + ".key");
RandomAccessFile keyFile = new RandomAccessFile(keyPath, "r");
keyFile.read(key);
keyFile.read(iv);
keyFile.close();
file = new RandomAccessFile(path, "r");
file.seek(dataSpec.position);
fileOffset = (int) dataSpec.position;
bytesRemaining = dataSpec.length == C.LENGTH_UNSET ? file.length() - dataSpec.position : dataSpec.length;
if (bytesRemaining < 0) {
throw new EOFException();
}
} catch (IOException e) {
throw new EncryptedFileDataSourceException(e);
}
opened = true;
if (listener != null) {
listener.onTransferStart(this, dataSpec, false);
}
return bytesRemaining;
}
public static IByteSource createSource(final InputStream input) {
return () -> {
final int b = input.read();
if (b < 0) throw new EOFException();
return b;
};
}
private static byte[] getBytes(URL url) throws IOException {
URLConnection uc = url.openConnection();
if (uc instanceof java.net.HttpURLConnection) {
java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
int code = huc.getResponseCode();
if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
throw new IOException("open HTTP connection failed.");
}
}
int len = uc.getContentLength();
// Fixed #4507227: Slow performance to load
// class and resources. [stanleyh]
//
// Use buffered input stream [stanleyh]
InputStream in = new BufferedInputStream(uc.getInputStream());
byte[] b;
try {
b = IOUtils.readAllBytes(in);
if (len != -1 && b.length != len)
throw new EOFException("Expected:" + len + ", read:" + b.length);
} finally {
in.close();
}
return b;
}
private boolean refill() throws IOException {
if (!remaining() && (limit = in.read(buf, 0, capacity)) <= 0) {
throw new EOFException("Attempt to read after eof.");
}
position = 0;
return true;
}
public void skipBytes(long count) throws EOFException, IOException {
long remaining = count;
while (remaining > 0) {
long skipped = maybeSkip(remaining);
if (skipped <= 0) {
break;
}
remaining -= skipped;
}
if (remaining > 0) {
throw new EOFException();
}
}
@Override
public int read() throws IOException {
try {
return inputView.readUnsignedByte();
} catch (EOFException e) {
// translate between DataInput and InputStream,
// DataInput signals EOF by exception, InputStream does it by returning -1
return -1;
}
}
@Override
public void readFully(long position, byte[] buffer) throws IOException {
int l = read(position, buffer, 0, buffer.length);
if (l < buffer.length) {
throw new EOFException();
}
}
@Override
public void flush() throws IOException {
buffer.flip();
while (buffer.remaining() > 0) {
selector.select();
if (!selector.isOpen()) {
throw new EOFException();
}
socket.write(buffer);
}
buffer.clear();
}
/**
* Constructs object, reading in all values from index
* @param dir Directory containing Preread index
* @throws IOException If an I/O error occurs
*/
public IndexFile(final File dir) throws IOException {
mPrereadArm = PrereadArm.UNKNOWN;
mPrereadType = PrereadType.UNKNOWN;
mSdfId = new SdfId(0);
final File index = new File(dir, SdfFileUtils.INDEX_FILENAME);
try (DataInputStream indexStream = new DataInputStream(new BufferedInputStream(new FileInputStream(index), FileUtils.BUFFERED_STREAM_SIZE))) {
final PrereadHashFunction headerHash = new PrereadHashFunction();
version1Load(indexStream, headerHash, dir);
if (mVersion > VERSION) {
throw new NoTalkbackSlimException("The SDF " + dir + " has been created with a newer version of RTG tools and cannot be read with this version.");
}
loadVersion3Fields(indexStream, headerHash);
loadVersion4Fields(indexStream, headerHash, dir);
loadVersion6Fields(indexStream, headerHash);
loadVersion8Fields(indexStream, headerHash);
loadVersion9Fields();
loadVersion10Fields(indexStream, headerHash);
loadVersion12Fields(indexStream, headerHash);
loadVersion13Fields(indexStream, headerHash);
checksumLoad(indexStream, headerHash, dir);
} catch (final EOFException e) {
throw new CorruptSdfException(dir);
}
}
/**
* Reads a little-endian 4 byte signed integer from the stream.
*
* @return The integer value.
* @throws EOFException
* On insufficient data for the integer.
* @throws IOException
* On a failure reading the integer.
*/
protected int readIntSuppressTimeoutOnNonFirstByte() throws EOFException,
IOException {
int read = 0;
int eofCheck = 0;
int result = 0;
read = myBsonIn.read();
eofCheck |= read;
result += (read << 0);
for (int i = Byte.SIZE; i < Integer.SIZE; i += Byte.SIZE) {
try {
read = myBsonIn.read();
}
catch (final SocketTimeoutException ste) {
// Bad - Only the first byte should timeout.
throw new IOException(ste);
}
eofCheck |= read;
result += (read << i);
}
if (eofCheck < 0) {
throw new EOFException("Remote connection closed: "
+ myRemoteAddress);
}
return result;
}