Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/java/io/FileInputStream.java
41152 views
1
/*
2
* Copyright (c) 1994, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package java.io;
27
28
import java.nio.channels.FileChannel;
29
import java.util.Arrays;
30
import jdk.internal.util.ArraysSupport;
31
import sun.nio.ch.FileChannelImpl;
32
33
/**
34
* A {@code FileInputStream} obtains input bytes
35
* from a file in a file system. What files
36
* are available depends on the host environment.
37
*
38
* <p>{@code FileInputStream} is meant for reading streams of raw bytes
39
* such as image data. For reading streams of characters, consider using
40
* {@code FileReader}.
41
*
42
* @apiNote
43
* To release resources used by this stream {@link #close} should be called
44
* directly or by try-with-resources. Subclasses are responsible for the cleanup
45
* of resources acquired by the subclass.
46
* Subclasses that override {@link #finalize} in order to perform cleanup
47
* should be modified to use alternative cleanup mechanisms such as
48
* {@link java.lang.ref.Cleaner} and remove the overriding {@code finalize} method.
49
*
50
* @implSpec
51
* If this FileInputStream has been subclassed and the {@link #close}
52
* method has been overridden, the {@link #close} method will be
53
* called when the FileInputStream is unreachable.
54
* Otherwise, it is implementation specific how the resource cleanup described in
55
* {@link #close} is performed.
56
*
57
* @author Arthur van Hoff
58
* @see java.io.File
59
* @see java.io.FileDescriptor
60
* @see java.io.FileOutputStream
61
* @see java.nio.file.Files#newInputStream
62
* @since 1.0
63
*/
64
public class FileInputStream extends InputStream
65
{
66
private static final int DEFAULT_BUFFER_SIZE = 8192;
67
68
/* File Descriptor - handle to the open file */
69
private final FileDescriptor fd;
70
71
/**
72
* The path of the referenced file
73
* (null if the stream is created with a file descriptor)
74
*/
75
private final String path;
76
77
private volatile FileChannel channel;
78
79
private final Object closeLock = new Object();
80
81
private volatile boolean closed;
82
83
/**
84
* Creates a {@code FileInputStream} by
85
* opening a connection to an actual file,
86
* the file named by the path name {@code name}
87
* in the file system. A new {@code FileDescriptor}
88
* object is created to represent this file
89
* connection.
90
* <p>
91
* First, if there is a security
92
* manager, its {@code checkRead} method
93
* is called with the {@code name} argument
94
* as its argument.
95
* <p>
96
* If the named file does not exist, is a directory rather than a regular
97
* file, or for some other reason cannot be opened for reading then a
98
* {@code FileNotFoundException} is thrown.
99
*
100
* @param name the system-dependent file name.
101
* @throws FileNotFoundException if the file does not exist,
102
* is a directory rather than a regular file,
103
* or for some other reason cannot be opened for
104
* reading.
105
* @throws SecurityException if a security manager exists and its
106
* {@code checkRead} method denies read access
107
* to the file.
108
* @see java.lang.SecurityManager#checkRead(java.lang.String)
109
*/
110
public FileInputStream(String name) throws FileNotFoundException {
111
this(name != null ? new File(name) : null);
112
}
113
114
/**
115
* Creates a {@code FileInputStream} by
116
* opening a connection to an actual file,
117
* the file named by the {@code File}
118
* object {@code file} in the file system.
119
* A new {@code FileDescriptor} object
120
* is created to represent this file connection.
121
* <p>
122
* First, if there is a security manager,
123
* its {@code checkRead} method is called
124
* with the path represented by the {@code file}
125
* argument as its argument.
126
* <p>
127
* If the named file does not exist, is a directory rather than a regular
128
* file, or for some other reason cannot be opened for reading then a
129
* {@code FileNotFoundException} is thrown.
130
*
131
* @param file the file to be opened for reading.
132
* @throws FileNotFoundException if the file does not exist,
133
* is a directory rather than a regular file,
134
* or for some other reason cannot be opened for
135
* reading.
136
* @throws SecurityException if a security manager exists and its
137
* {@code checkRead} method denies read access to the file.
138
* @see java.io.File#getPath()
139
* @see java.lang.SecurityManager#checkRead(java.lang.String)
140
*/
141
public FileInputStream(File file) throws FileNotFoundException {
142
String name = (file != null ? file.getPath() : null);
143
@SuppressWarnings("removal")
144
SecurityManager security = System.getSecurityManager();
145
if (security != null) {
146
security.checkRead(name);
147
}
148
if (name == null) {
149
throw new NullPointerException();
150
}
151
if (file.isInvalid()) {
152
throw new FileNotFoundException("Invalid file path");
153
}
154
fd = new FileDescriptor();
155
fd.attach(this);
156
path = name;
157
open(name);
158
FileCleanable.register(fd); // open set the fd, register the cleanup
159
}
160
161
/**
162
* Creates a {@code FileInputStream} by using the file descriptor
163
* {@code fdObj}, which represents an existing connection to an
164
* actual file in the file system.
165
* <p>
166
* If there is a security manager, its {@code checkRead} method is
167
* called with the file descriptor {@code fdObj} as its argument to
168
* see if it's ok to read the file descriptor. If read access is denied
169
* to the file descriptor a {@code SecurityException} is thrown.
170
* <p>
171
* If {@code fdObj} is null then a {@code NullPointerException}
172
* is thrown.
173
* <p>
174
* This constructor does not throw an exception if {@code fdObj}
175
* is {@link java.io.FileDescriptor#valid() invalid}.
176
* However, if the methods are invoked on the resulting stream to attempt
177
* I/O on the stream, an {@code IOException} is thrown.
178
*
179
* @param fdObj the file descriptor to be opened for reading.
180
* @throws SecurityException if a security manager exists and its
181
* {@code checkRead} method denies read access to the
182
* file descriptor.
183
* @see SecurityManager#checkRead(java.io.FileDescriptor)
184
*/
185
public FileInputStream(FileDescriptor fdObj) {
186
@SuppressWarnings("removal")
187
SecurityManager security = System.getSecurityManager();
188
if (fdObj == null) {
189
throw new NullPointerException();
190
}
191
if (security != null) {
192
security.checkRead(fdObj);
193
}
194
fd = fdObj;
195
path = null;
196
197
/*
198
* FileDescriptor is being shared by streams.
199
* Register this stream with FileDescriptor tracker.
200
*/
201
fd.attach(this);
202
}
203
204
/**
205
* Opens the specified file for reading.
206
* @param name the name of the file
207
*/
208
private native void open0(String name) throws FileNotFoundException;
209
210
// wrap native call to allow instrumentation
211
/**
212
* Opens the specified file for reading.
213
* @param name the name of the file
214
*/
215
private void open(String name) throws FileNotFoundException {
216
open0(name);
217
}
218
219
/**
220
* Reads a byte of data from this input stream. This method blocks
221
* if no input is yet available.
222
*
223
* @return the next byte of data, or {@code -1} if the end of the
224
* file is reached.
225
* @throws IOException if an I/O error occurs.
226
*/
227
public int read() throws IOException {
228
return read0();
229
}
230
231
private native int read0() throws IOException;
232
233
/**
234
* Reads a subarray as a sequence of bytes.
235
* @param b the data to be written
236
* @param off the start offset in the data
237
* @param len the number of bytes that are written
238
* @throws IOException If an I/O error has occurred.
239
*/
240
private native int readBytes(byte b[], int off, int len) throws IOException;
241
242
/**
243
* Reads up to {@code b.length} bytes of data from this input
244
* stream into an array of bytes. This method blocks until some input
245
* is available.
246
*
247
* @param b the buffer into which the data is read.
248
* @return the total number of bytes read into the buffer, or
249
* {@code -1} if there is no more data because the end of
250
* the file has been reached.
251
* @throws IOException if an I/O error occurs.
252
*/
253
public int read(byte b[]) throws IOException {
254
return readBytes(b, 0, b.length);
255
}
256
257
/**
258
* Reads up to {@code len} bytes of data from this input stream
259
* into an array of bytes. If {@code len} is not zero, the method
260
* blocks until some input is available; otherwise, no
261
* bytes are read and {@code 0} is returned.
262
*
263
* @param b the buffer into which the data is read.
264
* @param off the start offset in the destination array {@code b}
265
* @param len the maximum number of bytes read.
266
* @return the total number of bytes read into the buffer, or
267
* {@code -1} if there is no more data because the end of
268
* the file has been reached.
269
* @throws NullPointerException If {@code b} is {@code null}.
270
* @throws IndexOutOfBoundsException If {@code off} is negative,
271
* {@code len} is negative, or {@code len} is greater than
272
* {@code b.length - off}
273
* @throws IOException if an I/O error occurs.
274
*/
275
public int read(byte b[], int off, int len) throws IOException {
276
return readBytes(b, off, len);
277
}
278
279
public byte[] readAllBytes() throws IOException {
280
long length = length();
281
long position = position();
282
long size = length - position;
283
284
if (length <= 0 || size <= 0)
285
return super.readAllBytes();
286
287
if (size > (long) Integer.MAX_VALUE) {
288
String msg =
289
String.format("Required array size too large for %s: %d = %d - %d",
290
path, size, length, position);
291
throw new OutOfMemoryError(msg);
292
}
293
294
int capacity = (int)size;
295
byte[] buf = new byte[capacity];
296
297
int nread = 0;
298
int n;
299
for (;;) {
300
// read to EOF which may read more or less than initial size, e.g.,
301
// file is truncated while we are reading
302
while ((n = read(buf, nread, capacity - nread)) > 0)
303
nread += n;
304
305
// if last call to read() returned -1, we are done; otherwise,
306
// try to read one more byte and if that fails we're done too
307
if (n < 0 || (n = read()) < 0)
308
break;
309
310
// one more byte was read; need to allocate a larger buffer
311
capacity = Math.max(ArraysSupport.newLength(capacity,
312
1, // min growth
313
capacity), // pref growth
314
DEFAULT_BUFFER_SIZE);
315
buf = Arrays.copyOf(buf, capacity);
316
buf[nread++] = (byte)n;
317
}
318
return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
319
}
320
321
public byte[] readNBytes(int len) throws IOException {
322
if (len < 0)
323
throw new IllegalArgumentException("len < 0");
324
if (len == 0)
325
return new byte[0];
326
327
long length = length();
328
long position = position();
329
long size = length - position;
330
331
if (length <= 0 || size <= 0)
332
return super.readNBytes(len);
333
334
int capacity = (int)Math.min(len, size);
335
byte[] buf = new byte[capacity];
336
337
int remaining = capacity;
338
int nread = 0;
339
int n;
340
do {
341
n = read(buf, nread, remaining);
342
if (n > 0 ) {
343
nread += n;
344
remaining -= n;
345
} else if (n == 0) {
346
// Block until a byte is read or EOF is detected
347
byte b = (byte)read();
348
if (b == -1 )
349
break;
350
buf[nread++] = b;
351
remaining--;
352
}
353
} while (n >= 0 && remaining > 0);
354
return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
355
}
356
357
private long length() throws IOException {
358
return length0();
359
}
360
private native long length0() throws IOException;
361
362
private long position() throws IOException {
363
return position0();
364
}
365
private native long position0() throws IOException;
366
367
/**
368
* Skips over and discards {@code n} bytes of data from the
369
* input stream.
370
*
371
* <p>The {@code skip} method may, for a variety of
372
* reasons, end up skipping over some smaller number of bytes,
373
* possibly {@code 0}. If {@code n} is negative, the method
374
* will try to skip backwards. In case the backing file does not support
375
* backward skip at its current position, an {@code IOException} is
376
* thrown. The actual number of bytes skipped is returned. If it skips
377
* forwards, it returns a positive value. If it skips backwards, it
378
* returns a negative value.
379
*
380
* <p>This method may skip more bytes than what are remaining in the
381
* backing file. This produces no exception and the number of bytes skipped
382
* may include some number of bytes that were beyond the EOF of the
383
* backing file. Attempting to read from the stream after skipping past
384
* the end will result in -1 indicating the end of the file.
385
*
386
* @param n the number of bytes to be skipped.
387
* @return the actual number of bytes skipped.
388
* @throws IOException if n is negative, if the stream does not
389
* support seek, or if an I/O error occurs.
390
*/
391
public long skip(long n) throws IOException {
392
return skip0(n);
393
}
394
395
private native long skip0(long n) throws IOException;
396
397
/**
398
* Returns an estimate of the number of remaining bytes that can be read (or
399
* skipped over) from this input stream without blocking by the next
400
* invocation of a method for this input stream. Returns 0 when the file
401
* position is beyond EOF. The next invocation might be the same thread
402
* or another thread. A single read or skip of this many bytes will not
403
* block, but may read or skip fewer bytes.
404
*
405
* <p> In some cases, a non-blocking read (or skip) may appear to be
406
* blocked when it is merely slow, for example when reading large
407
* files over slow networks.
408
*
409
* @return an estimate of the number of remaining bytes that can be read
410
* (or skipped over) from this input stream without blocking.
411
* @throws IOException if this file input stream has been closed by calling
412
* {@code close} or an I/O error occurs.
413
*/
414
public int available() throws IOException {
415
return available0();
416
}
417
418
private native int available0() throws IOException;
419
420
/**
421
* Closes this file input stream and releases any system resources
422
* associated with the stream.
423
*
424
* <p> If this stream has an associated channel then the channel is closed
425
* as well.
426
*
427
* @apiNote
428
* Overriding {@link #close} to perform cleanup actions is reliable
429
* only when called directly or when called by try-with-resources.
430
* Do not depend on finalization to invoke {@code close};
431
* finalization is not reliable and is deprecated.
432
* If cleanup of native resources is needed, other mechanisms such as
433
* {@linkplain java.lang.ref.Cleaner} should be used.
434
*
435
* @throws IOException if an I/O error occurs.
436
*
437
* @revised 1.4
438
*/
439
public void close() throws IOException {
440
if (closed) {
441
return;
442
}
443
synchronized (closeLock) {
444
if (closed) {
445
return;
446
}
447
closed = true;
448
}
449
450
FileChannel fc = channel;
451
if (fc != null) {
452
// possible race with getChannel(), benign since
453
// FileChannel.close is final and idempotent
454
fc.close();
455
}
456
457
fd.closeAll(new Closeable() {
458
public void close() throws IOException {
459
fd.close();
460
}
461
});
462
}
463
464
/**
465
* Returns the {@code FileDescriptor}
466
* object that represents the connection to
467
* the actual file in the file system being
468
* used by this {@code FileInputStream}.
469
*
470
* @return the file descriptor object associated with this stream.
471
* @throws IOException if an I/O error occurs.
472
* @see java.io.FileDescriptor
473
*/
474
public final FileDescriptor getFD() throws IOException {
475
if (fd != null) {
476
return fd;
477
}
478
throw new IOException();
479
}
480
481
/**
482
* Returns the unique {@link java.nio.channels.FileChannel FileChannel}
483
* object associated with this file input stream.
484
*
485
* <p> The initial {@link java.nio.channels.FileChannel#position()
486
* position} of the returned channel will be equal to the
487
* number of bytes read from the file so far. Reading bytes from this
488
* stream will increment the channel's position. Changing the channel's
489
* position, either explicitly or by reading, will change this stream's
490
* file position.
491
*
492
* @return the file channel associated with this file input stream
493
*
494
* @since 1.4
495
*/
496
public FileChannel getChannel() {
497
FileChannel fc = this.channel;
498
if (fc == null) {
499
synchronized (this) {
500
fc = this.channel;
501
if (fc == null) {
502
this.channel = fc = FileChannelImpl.open(fd, path, true,
503
false, false, this);
504
if (closed) {
505
try {
506
// possible race with close(), benign since
507
// FileChannel.close is final and idempotent
508
fc.close();
509
} catch (IOException ioe) {
510
throw new InternalError(ioe); // should not happen
511
}
512
}
513
}
514
}
515
}
516
return fc;
517
}
518
519
private static native void initIDs();
520
521
static {
522
initIDs();
523
}
524
}
525
526