Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/java/nio/channels/FileChannel.java
41159 views
1
/*
2
* Copyright (c) 2000, 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.nio.channels;
27
28
import java.io.*;
29
import java.nio.ByteBuffer;
30
import java.nio.MappedByteBuffer;
31
import java.nio.channels.spi.AbstractInterruptibleChannel;
32
import java.nio.file.*;
33
import java.nio.file.attribute.FileAttribute;
34
import java.nio.file.spi.*;
35
import java.util.Set;
36
import java.util.HashSet;
37
import java.util.Collections;
38
39
/**
40
* A channel for reading, writing, mapping, and manipulating a file.
41
*
42
* <p> A file channel is a {@link SeekableByteChannel} that is connected to
43
* a file. It has a current <i>position</i> within its file which can
44
* be both {@link #position() <i>queried</i>} and {@link #position(long)
45
* <i>modified</i>}. The file itself contains a variable-length sequence
46
* of bytes that can be read and written and whose current {@link #size
47
* <i>size</i>} can be queried. The size of the file increases
48
* when bytes are written beyond its current size; the size of the file
49
* decreases when it is {@link #truncate <i>truncated</i>}. The
50
* file may also have some associated <i>metadata</i> such as access
51
* permissions, content type, and last-modification time; this class does not
52
* define methods for metadata access.
53
*
54
* <p> In addition to the familiar read, write, and close operations of byte
55
* channels, this class defines the following file-specific operations: </p>
56
*
57
* <ul>
58
*
59
* <li><p> Bytes may be {@link #read(ByteBuffer, long) read} or
60
* {@link #write(ByteBuffer, long) <i>written</i>} at an absolute
61
* position in a file in a way that does not affect the channel's current
62
* position. </p></li>
63
*
64
* <li><p> A region of a file may be {@link #map <i>mapped</i>}
65
* directly into memory; for large files this is often much more efficient
66
* than invoking the usual {@code read} or {@code write} methods.
67
* </p></li>
68
*
69
* <li><p> Updates made to a file may be {@link #force <i>forced
70
* out</i>} to the underlying storage device, ensuring that data are not
71
* lost in the event of a system crash. </p></li>
72
*
73
* <li><p> Bytes can be transferred from a file {@link #transferTo <i>to
74
* some other channel</i>}, and {@link #transferFrom <i>vice
75
* versa</i>}, in a way that can be optimized by many operating systems
76
* into a very fast transfer directly to or from the filesystem cache.
77
* </p></li>
78
*
79
* <li><p> A region of a file may be {@link FileLock <i>locked</i>}
80
* against access by other programs. </p></li>
81
*
82
* </ul>
83
*
84
* <p> File channels are safe for use by multiple concurrent threads. The
85
* {@link Channel#close close} method may be invoked at any time, as specified
86
* by the {@link Channel} interface. Only one operation that involves the
87
* channel's position or can change its file's size may be in progress at any
88
* given time; attempts to initiate a second such operation while the first is
89
* still in progress will block until the first operation completes. Other
90
* operations, in particular those that take an explicit position, may proceed
91
* concurrently; whether they in fact do so is dependent upon the underlying
92
* implementation and is therefore unspecified.
93
*
94
* <p> The view of a file provided by an instance of this class is guaranteed
95
* to be consistent with other views of the same file provided by other
96
* instances in the same program. The view provided by an instance of this
97
* class may or may not, however, be consistent with the views seen by other
98
* concurrently-running programs due to caching performed by the underlying
99
* operating system and delays induced by network-filesystem protocols. This
100
* is true regardless of the language in which these other programs are
101
* written, and whether they are running on the same machine or on some other
102
* machine. The exact nature of any such inconsistencies are system-dependent
103
* and are therefore unspecified.
104
*
105
* <p> A file channel is created by invoking one of the {@link #open open}
106
* methods defined by this class. A file channel can also be obtained from an
107
* existing {@link java.io.FileInputStream#getChannel FileInputStream}, {@link
108
* java.io.FileOutputStream#getChannel FileOutputStream}, or {@link
109
* java.io.RandomAccessFile#getChannel RandomAccessFile} object by invoking
110
* that object's {@code getChannel} method, which returns a file channel that
111
* is connected to the same underlying file. Where the file channel is obtained
112
* from an existing stream or random access file then the state of the file
113
* channel is intimately connected to that of the object whose {@code getChannel}
114
* method returned the channel. Changing the channel's position, whether
115
* explicitly or by reading or writing bytes, will change the file position of
116
* the originating object, and vice versa. Changing the file's length via the
117
* file channel will change the length seen via the originating object, and vice
118
* versa. Changing the file's content by writing bytes will change the content
119
* seen by the originating object, and vice versa.
120
*
121
* <a id="open-mode"></a> <p> At various points this class specifies that an
122
* instance that is "open for reading," "open for writing," or "open for
123
* reading and writing" is required. A channel obtained via the {@link
124
* java.io.FileInputStream#getChannel getChannel} method of a {@link
125
* java.io.FileInputStream} instance will be open for reading. A channel
126
* obtained via the {@link java.io.FileOutputStream#getChannel getChannel}
127
* method of a {@link java.io.FileOutputStream} instance will be open for
128
* writing. Finally, a channel obtained via the {@link
129
* java.io.RandomAccessFile#getChannel getChannel} method of a {@link
130
* java.io.RandomAccessFile} instance will be open for reading if the instance
131
* was created with mode {@code "r"} and will be open for reading and writing
132
* if the instance was created with mode {@code "rw"}.
133
*
134
* <a id="append-mode"></a><p> A file channel that is open for writing may be in
135
* <i>append mode</i>, for example if it was obtained from a file-output stream
136
* that was created by invoking the {@link
137
* java.io.FileOutputStream#FileOutputStream(java.io.File,boolean)
138
* FileOutputStream(File,boolean)} constructor and passing {@code true} for
139
* the second parameter. In this mode each invocation of a relative write
140
* operation first advances the position to the end of the file and then writes
141
* the requested data. Whether the advancement of the position and the writing
142
* of the data are done in a single atomic operation is system-dependent and
143
* therefore unspecified.
144
*
145
* @see java.io.FileInputStream#getChannel()
146
* @see java.io.FileOutputStream#getChannel()
147
* @see java.io.RandomAccessFile#getChannel()
148
*
149
* @author Mark Reinhold
150
* @author Mike McCloskey
151
* @author JSR-51 Expert Group
152
* @since 1.4
153
*/
154
155
public abstract class FileChannel
156
extends AbstractInterruptibleChannel
157
implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel
158
{
159
/**
160
* Initializes a new instance of this class.
161
*/
162
protected FileChannel() { }
163
164
/**
165
* Opens or creates a file, returning a file channel to access the file.
166
*
167
* <p> The {@code options} parameter determines how the file is opened.
168
* The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE
169
* WRITE} options determine if the file should be opened for reading and/or
170
* writing. If neither option (or the {@link StandardOpenOption#APPEND APPEND}
171
* option) is contained in the array then the file is opened for reading.
172
* By default reading or writing commences at the beginning of the file.
173
*
174
* <p> In the addition to {@code READ} and {@code WRITE}, the following
175
* options may be present:
176
*
177
* <table class="striped">
178
* <caption style="display:none">additional options</caption>
179
* <thead>
180
* <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr>
181
* </thead>
182
* <tbody>
183
* <tr>
184
* <th scope="row"> {@link StandardOpenOption#APPEND APPEND} </th>
185
* <td> If this option is present then the file is opened for writing and
186
* each invocation of the channel's {@code write} method first advances
187
* the position to the end of the file and then writes the requested
188
* data. Whether the advancement of the position and the writing of the
189
* data are done in a single atomic operation is system-dependent and
190
* therefore unspecified. This option may not be used in conjunction
191
* with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td>
192
* </tr>
193
* <tr>
194
* <th scope="row"> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </th>
195
* <td> If this option is present then the existing file is truncated to
196
* a size of 0 bytes. This option is ignored when the file is opened only
197
* for reading. </td>
198
* </tr>
199
* <tr>
200
* <th scope="row"> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </th>
201
* <td> If this option is present then a new file is created, failing if
202
* the file already exists. When creating a file the check for the
203
* existence of the file and the creation of the file if it does not exist
204
* is atomic with respect to other file system operations. This option is
205
* ignored when the file is opened only for reading. </td>
206
* </tr>
207
* <tr>
208
* <th scope="row" > {@link StandardOpenOption#CREATE CREATE} </th>
209
* <td> If this option is present then an existing file is opened if it
210
* exists, otherwise a new file is created. When creating a file the check
211
* for the existence of the file and the creation of the file if it does
212
* not exist is atomic with respect to other file system operations. This
213
* option is ignored if the {@code CREATE_NEW} option is also present or
214
* the file is opened only for reading. </td>
215
* </tr>
216
* <tr>
217
* <th scope="row" > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </th>
218
* <td> When this option is present then the implementation makes a
219
* <em>best effort</em> attempt to delete the file when closed by
220
* the {@link #close close} method. If the {@code close} method is not
221
* invoked then a <em>best effort</em> attempt is made to delete the file
222
* when the Java virtual machine terminates. </td>
223
* </tr>
224
* <tr>
225
* <th scope="row">{@link StandardOpenOption#SPARSE SPARSE} </th>
226
* <td> When creating a new file this option is a <em>hint</em> that the
227
* new file will be sparse. This option is ignored when not creating
228
* a new file. </td>
229
* </tr>
230
* <tr>
231
* <th scope="row"> {@link StandardOpenOption#SYNC SYNC} </th>
232
* <td> Requires that every update to the file's content or metadata be
233
* written synchronously to the underlying storage device. (see <a
234
* href="../file/package-summary.html#integrity"> Synchronized I/O file
235
* integrity</a>). </td>
236
* </tr>
237
* <tr>
238
* <th scope="row"> {@link StandardOpenOption#DSYNC DSYNC} </th>
239
* <td> Requires that every update to the file's content be written
240
* synchronously to the underlying storage device. (see <a
241
* href="../file/package-summary.html#integrity"> Synchronized I/O file
242
* integrity</a>). </td>
243
* </tr>
244
* </tbody>
245
* </table>
246
*
247
* <p> An implementation may also support additional options.
248
*
249
* <p> The {@code attrs} parameter is an optional array of file {@link
250
* FileAttribute file-attributes} to set atomically when creating the file.
251
*
252
* <p> The new channel is created by invoking the {@link
253
* FileSystemProvider#newFileChannel newFileChannel} method on the
254
* provider that created the {@code Path}.
255
*
256
* @param path
257
* The path of the file to open or create
258
* @param options
259
* Options specifying how the file is opened
260
* @param attrs
261
* An optional list of file attributes to set atomically when
262
* creating the file
263
*
264
* @return A new file channel
265
*
266
* @throws IllegalArgumentException
267
* If the set contains an invalid combination of options
268
* @throws UnsupportedOperationException
269
* If the {@code path} is associated with a provider that does not
270
* support creating file channels, or an unsupported open option is
271
* specified, or the array contains an attribute that cannot be set
272
* atomically when creating the file
273
* @throws FileAlreadyExistsException
274
* If a file of that name already exists and the {@link
275
* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified
276
* and the file is being opened for writing
277
* <i>(<a href="../file/package-summary.html#optspecex">optional
278
* specific exception</a>)</i>
279
* @throws IOException
280
* If an I/O error occurs
281
* @throws SecurityException
282
* If a security manager is installed and it denies an
283
* unspecified permission required by the implementation.
284
* In the case of the default provider, the {@link
285
* SecurityManager#checkRead(String)} method is invoked to check
286
* read access if the file is opened for reading. The {@link
287
* SecurityManager#checkWrite(String)} method is invoked to check
288
* write access if the file is opened for writing
289
*
290
* @since 1.7
291
*/
292
public static FileChannel open(Path path,
293
Set<? extends OpenOption> options,
294
FileAttribute<?>... attrs)
295
throws IOException
296
{
297
FileSystemProvider provider = path.getFileSystem().provider();
298
return provider.newFileChannel(path, options, attrs);
299
}
300
301
@SuppressWarnings({"unchecked", "rawtypes"}) // generic array construction
302
private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0];
303
304
/**
305
* Opens or creates a file, returning a file channel to access the file.
306
*
307
* <p> An invocation of this method behaves in exactly the same way as the
308
* invocation
309
* <pre>
310
* fc.{@link #open(Path,Set,FileAttribute[]) open}(file, opts, new FileAttribute&lt;?&gt;[0]);
311
* </pre>
312
* where {@code opts} is a set of the options specified in the {@code
313
* options} array.
314
*
315
* @param path
316
* The path of the file to open or create
317
* @param options
318
* Options specifying how the file is opened
319
*
320
* @return A new file channel
321
*
322
* @throws IllegalArgumentException
323
* If the set contains an invalid combination of options
324
* @throws UnsupportedOperationException
325
* If the {@code path} is associated with a provider that does not
326
* support creating file channels, or an unsupported open option is
327
* specified
328
* @throws FileAlreadyExistsException
329
* If a file of that name already exists and the {@link
330
* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified
331
* and the file is being opened for writing
332
* <i>(<a href="../file/package-summary.html#optspecex">optional
333
* specific exception</a>)</i>
334
* @throws IOException
335
* If an I/O error occurs
336
* @throws SecurityException
337
* If a security manager is installed and it denies an
338
* unspecified permission required by the implementation.
339
* In the case of the default provider, the {@link
340
* SecurityManager#checkRead(String)} method is invoked to check
341
* read access if the file is opened for reading. The {@link
342
* SecurityManager#checkWrite(String)} method is invoked to check
343
* write access if the file is opened for writing
344
*
345
* @since 1.7
346
*/
347
public static FileChannel open(Path path, OpenOption... options)
348
throws IOException
349
{
350
Set<OpenOption> set;
351
if (options.length == 0) {
352
set = Collections.emptySet();
353
} else {
354
set = new HashSet<>();
355
Collections.addAll(set, options);
356
}
357
return open(path, set, NO_ATTRIBUTES);
358
}
359
360
// -- Channel operations --
361
362
/**
363
* Reads a sequence of bytes from this channel into the given buffer.
364
*
365
* <p> Bytes are read starting at this channel's current file position, and
366
* then the file position is updated with the number of bytes actually
367
* read. Otherwise this method behaves exactly as specified in the {@link
368
* ReadableByteChannel} interface. </p>
369
*/
370
public abstract int read(ByteBuffer dst) throws IOException;
371
372
/**
373
* Reads a sequence of bytes from this channel into a subsequence of the
374
* given buffers.
375
*
376
* <p> Bytes are read starting at this channel's current file position, and
377
* then the file position is updated with the number of bytes actually
378
* read. Otherwise this method behaves exactly as specified in the {@link
379
* ScatteringByteChannel} interface. </p>
380
*/
381
public abstract long read(ByteBuffer[] dsts, int offset, int length)
382
throws IOException;
383
384
/**
385
* Reads a sequence of bytes from this channel into the given buffers.
386
*
387
* <p> Bytes are read starting at this channel's current file position, and
388
* then the file position is updated with the number of bytes actually
389
* read. Otherwise this method behaves exactly as specified in the {@link
390
* ScatteringByteChannel} interface. </p>
391
*/
392
public final long read(ByteBuffer[] dsts) throws IOException {
393
return read(dsts, 0, dsts.length);
394
}
395
396
/**
397
* Writes a sequence of bytes to this channel from the given buffer.
398
*
399
* <p> Bytes are written starting at this channel's current file position
400
* unless the channel is in append mode, in which case the position is
401
* first advanced to the end of the file. The file is grown, if necessary,
402
* to accommodate the written bytes, and then the file position is updated
403
* with the number of bytes actually written. Otherwise this method
404
* behaves exactly as specified by the {@link WritableByteChannel}
405
* interface. </p>
406
*/
407
public abstract int write(ByteBuffer src) throws IOException;
408
409
/**
410
* Writes a sequence of bytes to this channel from a subsequence of the
411
* given buffers.
412
*
413
* <p> Bytes are written starting at this channel's current file position
414
* unless the channel is in append mode, in which case the position is
415
* first advanced to the end of the file. The file is grown, if necessary,
416
* to accommodate the written bytes, and then the file position is updated
417
* with the number of bytes actually written. Otherwise this method
418
* behaves exactly as specified in the {@link GatheringByteChannel}
419
* interface. </p>
420
*/
421
public abstract long write(ByteBuffer[] srcs, int offset, int length)
422
throws IOException;
423
424
/**
425
* Writes a sequence of bytes to this channel from the given buffers.
426
*
427
* <p> Bytes are written starting at this channel's current file position
428
* unless the channel is in append mode, in which case the position is
429
* first advanced to the end of the file. The file is grown, if necessary,
430
* to accommodate the written bytes, and then the file position is updated
431
* with the number of bytes actually written. Otherwise this method
432
* behaves exactly as specified in the {@link GatheringByteChannel}
433
* interface. </p>
434
*/
435
public final long write(ByteBuffer[] srcs) throws IOException {
436
return write(srcs, 0, srcs.length);
437
}
438
439
440
// -- Other operations --
441
442
/**
443
* Returns this channel's file position.
444
*
445
* @return This channel's file position,
446
* a non-negative integer counting the number of bytes
447
* from the beginning of the file to the current position
448
*
449
* @throws ClosedChannelException
450
* If this channel is closed
451
*
452
* @throws IOException
453
* If some other I/O error occurs
454
*/
455
public abstract long position() throws IOException;
456
457
/**
458
* Sets this channel's file position.
459
*
460
* <p> Setting the position to a value that is greater than the file's
461
* current size is legal but does not change the size of the file. A later
462
* attempt to read bytes at such a position will immediately return an
463
* end-of-file indication. A later attempt to write bytes at such a
464
* position will cause the file to be grown to accommodate the new bytes;
465
* the values of any bytes between the previous end-of-file and the
466
* newly-written bytes are unspecified. </p>
467
*
468
* @param newPosition
469
* The new position, a non-negative integer counting
470
* the number of bytes from the beginning of the file
471
*
472
* @return This file channel
473
*
474
* @throws ClosedChannelException
475
* If this channel is closed
476
*
477
* @throws IllegalArgumentException
478
* If the new position is negative
479
*
480
* @throws IOException
481
* If some other I/O error occurs
482
*/
483
public abstract FileChannel position(long newPosition) throws IOException;
484
485
/**
486
* Returns the current size of this channel's file.
487
*
488
* @return The current size of this channel's file,
489
* measured in bytes
490
*
491
* @throws ClosedChannelException
492
* If this channel is closed
493
*
494
* @throws IOException
495
* If some other I/O error occurs
496
*/
497
public abstract long size() throws IOException;
498
499
/**
500
* Truncates this channel's file to the given size.
501
*
502
* <p> If the given size is less than the file's current size then the file
503
* is truncated, discarding any bytes beyond the new end of the file. If
504
* the given size is greater than or equal to the file's current size then
505
* the file is not modified. In either case, if this channel's file
506
* position is greater than the given size then it is set to that size.
507
* </p>
508
*
509
* @param size
510
* The new size, a non-negative byte count
511
*
512
* @return This file channel
513
*
514
* @throws NonWritableChannelException
515
* If this channel was not opened for writing
516
*
517
* @throws ClosedChannelException
518
* If this channel is closed
519
*
520
* @throws IllegalArgumentException
521
* If the new size is negative
522
*
523
* @throws IOException
524
* If some other I/O error occurs
525
*/
526
public abstract FileChannel truncate(long size) throws IOException;
527
528
/**
529
* Forces any updates to this channel's file to be written to the storage
530
* device that contains it.
531
*
532
* <p> If this channel's file resides on a local storage device then when
533
* this method returns it is guaranteed that all changes made to the file
534
* since this channel was created, or since this method was last invoked,
535
* will have been written to that device. This is useful for ensuring that
536
* critical information is not lost in the event of a system crash.
537
*
538
* <p> If the file does not reside on a local device then no such guarantee
539
* is made.
540
*
541
* <p> The {@code metaData} parameter can be used to limit the number of
542
* I/O operations that this method is required to perform. Passing
543
* {@code false} for this parameter indicates that only updates to the
544
* file's content need be written to storage; passing {@code true}
545
* indicates that updates to both the file's content and metadata must be
546
* written, which generally requires at least one more I/O operation.
547
* Whether this parameter actually has any effect is dependent upon the
548
* underlying operating system and is therefore unspecified.
549
*
550
* <p> Invoking this method may cause an I/O operation to occur even if the
551
* channel was only opened for reading. Some operating systems, for
552
* example, maintain a last-access time as part of a file's metadata, and
553
* this time is updated whenever the file is read. Whether or not this is
554
* actually done is system-dependent and is therefore unspecified.
555
*
556
* <p> This method is only guaranteed to force changes that were made to
557
* this channel's file via the methods defined in this class. It may or
558
* may not force changes that were made by modifying the content of a
559
* {@link MappedByteBuffer <i>mapped byte buffer</i>} obtained by
560
* invoking the {@link #map map} method. Invoking the {@link
561
* MappedByteBuffer#force force} method of the mapped byte buffer will
562
* force changes made to the buffer's content to be written. </p>
563
*
564
* @param metaData
565
* If {@code true} then this method is required to force changes
566
* to both the file's content and metadata to be written to
567
* storage; otherwise, it need only force content changes to be
568
* written
569
*
570
* @throws ClosedChannelException
571
* If this channel is closed
572
*
573
* @throws IOException
574
* If some other I/O error occurs
575
*/
576
public abstract void force(boolean metaData) throws IOException;
577
578
/**
579
* Transfers bytes from this channel's file to the given writable byte
580
* channel.
581
*
582
* <p> An attempt is made to read up to {@code count} bytes starting at
583
* the given {@code position} in this channel's file and write them to the
584
* target channel. An invocation of this method may or may not transfer
585
* all of the requested bytes; whether or not it does so depends upon the
586
* natures and states of the channels. Fewer than the requested number of
587
* bytes are transferred if this channel's file contains fewer than
588
* {@code count} bytes starting at the given {@code position}, or if the
589
* target channel is non-blocking and it has fewer than {@code count}
590
* bytes free in its output buffer.
591
*
592
* <p> This method does not modify this channel's position. If the given
593
* position is greater than the file's current size then no bytes are
594
* transferred. If the target channel has a position then bytes are
595
* written starting at that position and then the position is incremented
596
* by the number of bytes written.
597
*
598
* <p> This method is potentially much more efficient than a simple loop
599
* that reads from this channel and writes to the target channel. Many
600
* operating systems can transfer bytes directly from the filesystem cache
601
* to the target channel without actually copying them. </p>
602
*
603
* @param position
604
* The position within the file at which the transfer is to begin;
605
* must be non-negative
606
*
607
* @param count
608
* The maximum number of bytes to be transferred; must be
609
* non-negative
610
*
611
* @param target
612
* The target channel
613
*
614
* @return The number of bytes, possibly zero,
615
* that were actually transferred
616
*
617
* @throws IllegalArgumentException
618
* If the preconditions on the parameters do not hold
619
*
620
* @throws NonReadableChannelException
621
* If this channel was not opened for reading
622
*
623
* @throws NonWritableChannelException
624
* If the target channel was not opened for writing
625
*
626
* @throws ClosedChannelException
627
* If either this channel or the target channel is closed
628
*
629
* @throws AsynchronousCloseException
630
* If another thread closes either channel
631
* while the transfer is in progress
632
*
633
* @throws ClosedByInterruptException
634
* If another thread interrupts the current thread while the
635
* transfer is in progress, thereby closing both channels and
636
* setting the current thread's interrupt status
637
*
638
* @throws IOException
639
* If some other I/O error occurs
640
*/
641
public abstract long transferTo(long position, long count,
642
WritableByteChannel target)
643
throws IOException;
644
645
/**
646
* Transfers bytes into this channel's file from the given readable byte
647
* channel.
648
*
649
* <p> An attempt is made to read up to {@code count} bytes from the
650
* source channel and write them to this channel's file starting at the
651
* given {@code position}. An invocation of this method may or may not
652
* transfer all of the requested bytes; whether or not it does so depends
653
* upon the natures and states of the channels. Fewer than the requested
654
* number of bytes will be transferred if the source channel has fewer than
655
* {@code count} bytes remaining, or if the source channel is non-blocking
656
* and has fewer than {@code count} bytes immediately available in its
657
* input buffer. No bytes are transferred, and zero is returned, if the
658
* source has reached end-of-stream.
659
*
660
* <p> This method does not modify this channel's position. If the given
661
* position is greater than the file's current size then no bytes are
662
* transferred. If the source channel has a position then bytes are read
663
* starting at that position and then the position is incremented by the
664
* number of bytes read.
665
*
666
* <p> This method is potentially much more efficient than a simple loop
667
* that reads from the source channel and writes to this channel. Many
668
* operating systems can transfer bytes directly from the source channel
669
* into the filesystem cache without actually copying them. </p>
670
*
671
* @param src
672
* The source channel
673
*
674
* @param position
675
* The position within the file at which the transfer is to begin;
676
* must be non-negative
677
*
678
* @param count
679
* The maximum number of bytes to be transferred; must be
680
* non-negative
681
*
682
* @return The number of bytes, possibly zero,
683
* that were actually transferred
684
*
685
* @throws IllegalArgumentException
686
* If the preconditions on the parameters do not hold
687
*
688
* @throws NonReadableChannelException
689
* If the source channel was not opened for reading
690
*
691
* @throws NonWritableChannelException
692
* If this channel was not opened for writing
693
*
694
* @throws ClosedChannelException
695
* If either this channel or the source channel is closed
696
*
697
* @throws AsynchronousCloseException
698
* If another thread closes either channel
699
* while the transfer is in progress
700
*
701
* @throws ClosedByInterruptException
702
* If another thread interrupts the current thread while the
703
* transfer is in progress, thereby closing both channels and
704
* setting the current thread's interrupt status
705
*
706
* @throws IOException
707
* If some other I/O error occurs
708
*/
709
public abstract long transferFrom(ReadableByteChannel src,
710
long position, long count)
711
throws IOException;
712
713
/**
714
* Reads a sequence of bytes from this channel into the given buffer,
715
* starting at the given file position.
716
*
717
* <p> This method works in the same manner as the {@link
718
* #read(ByteBuffer)} method, except that bytes are read starting at the
719
* given file position rather than at the channel's current position. This
720
* method does not modify this channel's position. If the given position
721
* is greater than the file's current size then no bytes are read. </p>
722
*
723
* @param dst
724
* The buffer into which bytes are to be transferred
725
*
726
* @param position
727
* The file position at which the transfer is to begin;
728
* must be non-negative
729
*
730
* @return The number of bytes read, possibly zero, or {@code -1} if the
731
* given position is greater than or equal to the file's current
732
* size
733
*
734
* @throws IllegalArgumentException
735
* If the position is negative or the buffer is read-only
736
*
737
* @throws NonReadableChannelException
738
* If this channel was not opened for reading
739
*
740
* @throws ClosedChannelException
741
* If this channel is closed
742
*
743
* @throws AsynchronousCloseException
744
* If another thread closes this channel
745
* while the read operation is in progress
746
*
747
* @throws ClosedByInterruptException
748
* If another thread interrupts the current thread
749
* while the read operation is in progress, thereby
750
* closing the channel and setting the current thread's
751
* interrupt status
752
*
753
* @throws IOException
754
* If some other I/O error occurs
755
*/
756
public abstract int read(ByteBuffer dst, long position) throws IOException;
757
758
/**
759
* Writes a sequence of bytes to this channel from the given buffer,
760
* starting at the given file position.
761
*
762
* <p> This method works in the same manner as the {@link
763
* #write(ByteBuffer)} method, except that bytes are written starting at
764
* the given file position rather than at the channel's current position.
765
* This method does not modify this channel's position. If the given
766
* position is greater than the file's current size then the file will be
767
* grown to accommodate the new bytes; the values of any bytes between the
768
* previous end-of-file and the newly-written bytes are unspecified. </p>
769
*
770
* @param src
771
* The buffer from which bytes are to be transferred
772
*
773
* @param position
774
* The file position at which the transfer is to begin;
775
* must be non-negative
776
*
777
* @return The number of bytes written, possibly zero
778
*
779
* @throws IllegalArgumentException
780
* If the position is negative
781
*
782
* @throws NonWritableChannelException
783
* If this channel was not opened for writing
784
*
785
* @throws ClosedChannelException
786
* If this channel is closed
787
*
788
* @throws AsynchronousCloseException
789
* If another thread closes this channel
790
* while the write operation is in progress
791
*
792
* @throws ClosedByInterruptException
793
* If another thread interrupts the current thread
794
* while the write operation is in progress, thereby
795
* closing the channel and setting the current thread's
796
* interrupt status
797
*
798
* @throws IOException
799
* If some other I/O error occurs
800
*/
801
public abstract int write(ByteBuffer src, long position) throws IOException;
802
803
804
// -- Memory-mapped buffers --
805
806
/**
807
* A file-mapping mode.
808
*
809
* @since 1.4
810
*
811
* @see java.nio.channels.FileChannel#map
812
*/
813
public static class MapMode {
814
815
/**
816
* Mode for a read-only mapping.
817
*/
818
public static final MapMode READ_ONLY
819
= new MapMode("READ_ONLY");
820
821
/**
822
* Mode for a read/write mapping.
823
*/
824
public static final MapMode READ_WRITE
825
= new MapMode("READ_WRITE");
826
827
/**
828
* Mode for a private (copy-on-write) mapping.
829
*/
830
public static final MapMode PRIVATE
831
= new MapMode("PRIVATE");
832
833
private final String name;
834
835
/**
836
* Constructs an instance of this class. This constructor may be used
837
* by code in java.base to create file mapping modes beyond the file
838
* mapping modes defined here.
839
* @param name the name of the map mode
840
*/
841
private MapMode(String name) {
842
this.name = name;
843
}
844
845
/**
846
* Returns a string describing this file-mapping mode.
847
*
848
* @return A descriptive string
849
*/
850
public String toString() {
851
return name;
852
}
853
854
}
855
856
/**
857
* Maps a region of this channel's file directly into memory.
858
*
859
* <p> The {@code mode} parameter specifies how the region of the file is
860
* mapped and may be one of the following modes:
861
*
862
* <ul>
863
*
864
* <li><p> <i>Read-only:</i> Any attempt to modify the resulting buffer
865
* will cause a {@link java.nio.ReadOnlyBufferException} to be thrown.
866
* ({@link MapMode#READ_ONLY MapMode.READ_ONLY}) </p></li>
867
*
868
* <li><p> <i>Read/write:</i> Changes made to the resulting buffer will
869
* eventually be propagated to the file; they may or may not be made
870
* visible to other programs that have mapped the same file. ({@link
871
* MapMode#READ_WRITE MapMode.READ_WRITE}) </p></li>
872
*
873
* <li><p> <i>Private:</i> Changes made to the resulting buffer will not
874
* be propagated to the file and will not be visible to other programs
875
* that have mapped the same file; instead, they will cause private
876
* copies of the modified portions of the buffer to be created. ({@link
877
* MapMode#PRIVATE MapMode.PRIVATE}) </p></li>
878
*
879
* </ul>
880
*
881
* <p> An implementation may support additional map modes.
882
*
883
* <p> For a read-only mapping, this channel must have been opened for
884
* reading; for a read/write or private mapping, this channel must have
885
* been opened for both reading and writing.
886
*
887
* <p> The {@link MappedByteBuffer <i>mapped byte buffer</i>}
888
* returned by this method will have a position of zero and a limit and
889
* capacity of {@code size}; its mark will be undefined. The buffer and
890
* the mapping that it represents will remain valid until the buffer itself
891
* is garbage-collected.
892
*
893
* <p> A mapping, once established, is not dependent upon the file channel
894
* that was used to create it. Closing the channel, in particular, has no
895
* effect upon the validity of the mapping.
896
*
897
* <p> Many of the details of memory-mapped files are inherently dependent
898
* upon the underlying operating system and are therefore unspecified. The
899
* behavior of this method when the requested region is not completely
900
* contained within this channel's file is unspecified. Whether changes
901
* made to the content or size of the underlying file, by this program or
902
* another, are propagated to the buffer is unspecified. The rate at which
903
* changes to the buffer are propagated to the file is unspecified.
904
*
905
* <p> For most operating systems, mapping a file into memory is more
906
* expensive than reading or writing a few tens of kilobytes of data via
907
* the usual {@link #read read} and {@link #write write} methods. From the
908
* standpoint of performance it is generally only worth mapping relatively
909
* large files into memory. </p>
910
*
911
* @param mode
912
* One of the constants {@link MapMode#READ_ONLY READ_ONLY}, {@link
913
* MapMode#READ_WRITE READ_WRITE}, or {@link MapMode#PRIVATE
914
* PRIVATE} defined in the {@link MapMode} class, according to
915
* whether the file is to be mapped read-only, read/write, or
916
* privately (copy-on-write), respectively, or an implementation
917
* specific map mode
918
*
919
* @param position
920
* The position within the file at which the mapped region
921
* is to start; must be non-negative
922
*
923
* @param size
924
* The size of the region to be mapped; must be non-negative and
925
* no greater than {@link java.lang.Integer#MAX_VALUE}
926
*
927
* @return The mapped byte buffer
928
*
929
* @throws NonReadableChannelException
930
* If the {@code mode} is {@link MapMode#READ_ONLY READ_ONLY} or
931
* an implementation specific map mode requiring read access
932
* but this channel was not opened for reading
933
*
934
* @throws NonWritableChannelException
935
* If the {@code mode} is {@link MapMode#READ_WRITE READ_WRITE}.
936
* {@link MapMode#PRIVATE PRIVATE} or an implementation specific
937
* map mode requiring write access but this channel was not
938
* opened for both reading and writing
939
*
940
* @throws IllegalArgumentException
941
* If the preconditions on the parameters do not hold
942
*
943
* @throws UnsupportedOperationException
944
* If an unsupported map mode is specified
945
*
946
* @throws IOException
947
* If some other I/O error occurs
948
*
949
* @see java.nio.channels.FileChannel.MapMode
950
* @see java.nio.MappedByteBuffer
951
*/
952
public abstract MappedByteBuffer map(MapMode mode, long position, long size)
953
throws IOException;
954
955
956
// -- Locks --
957
958
/**
959
* Acquires a lock on the given region of this channel's file.
960
*
961
* <p> An invocation of this method will block until the region can be
962
* locked, this channel is closed, or the invoking thread is interrupted,
963
* whichever comes first.
964
*
965
* <p> If this channel is closed by another thread during an invocation of
966
* this method then an {@link AsynchronousCloseException} will be thrown.
967
*
968
* <p> If the invoking thread is interrupted while waiting to acquire the
969
* lock then its interrupt status will be set and a {@link
970
* FileLockInterruptionException} will be thrown. If the invoker's
971
* interrupt status is set when this method is invoked then that exception
972
* will be thrown immediately; the thread's interrupt status will not be
973
* changed.
974
*
975
* <p> The region specified by the {@code position} and {@code size}
976
* parameters need not be contained within, or even overlap, the actual
977
* underlying file. Lock regions are fixed in size; if a locked region
978
* initially contains the end of the file and the file grows beyond the
979
* region then the new portion of the file will not be covered by the lock.
980
* If a file is expected to grow in size and a lock on the entire file is
981
* required then a region starting at zero, and no smaller than the
982
* expected maximum size of the file, should be locked. The zero-argument
983
* {@link #lock()} method simply locks a region of size {@link
984
* Long#MAX_VALUE}.
985
*
986
* <p> Some operating systems do not support shared locks, in which case a
987
* request for a shared lock is automatically converted into a request for
988
* an exclusive lock. Whether the newly-acquired lock is shared or
989
* exclusive may be tested by invoking the resulting lock object's {@link
990
* FileLock#isShared() isShared} method.
991
*
992
* <p> File locks are held on behalf of the entire Java virtual machine.
993
* They are not suitable for controlling access to a file by multiple
994
* threads within the same virtual machine. </p>
995
*
996
* @param position
997
* The position at which the locked region is to start; must be
998
* non-negative
999
*
1000
* @param size
1001
* The size of the locked region; must be non-negative, and the sum
1002
* {@code position}&nbsp;+&nbsp;{@code size} must be non-negative
1003
*
1004
* @param shared
1005
* {@code true} to request a shared lock, in which case this
1006
* channel must be open for reading (and possibly writing);
1007
* {@code false} to request an exclusive lock, in which case this
1008
* channel must be open for writing (and possibly reading)
1009
*
1010
* @return A lock object representing the newly-acquired lock
1011
*
1012
* @throws IllegalArgumentException
1013
* If the preconditions on the parameters do not hold
1014
*
1015
* @throws ClosedChannelException
1016
* If this channel is closed
1017
*
1018
* @throws AsynchronousCloseException
1019
* If another thread closes this channel while the invoking
1020
* thread is blocked in this method
1021
*
1022
* @throws FileLockInterruptionException
1023
* If the invoking thread is interrupted while blocked in this
1024
* method
1025
*
1026
* @throws OverlappingFileLockException
1027
* If a lock that overlaps the requested region is already held by
1028
* this Java virtual machine, or if another thread is already
1029
* blocked in this method and is attempting to lock an overlapping
1030
* region
1031
*
1032
* @throws NonReadableChannelException
1033
* If {@code shared} is {@code true} this channel was not
1034
* opened for reading
1035
*
1036
* @throws NonWritableChannelException
1037
* If {@code shared} is {@code false} but this channel was not
1038
* opened for writing
1039
*
1040
* @throws IOException
1041
* If some other I/O error occurs
1042
*
1043
* @see #lock()
1044
* @see #tryLock()
1045
* @see #tryLock(long,long,boolean)
1046
*/
1047
public abstract FileLock lock(long position, long size, boolean shared)
1048
throws IOException;
1049
1050
/**
1051
* Acquires an exclusive lock on this channel's file.
1052
*
1053
* <p> An invocation of this method of the form {@code fc.lock()} behaves
1054
* in exactly the same way as the invocation
1055
*
1056
* <pre>
1057
* fc.{@link #lock(long,long,boolean) lock}(0L, Long.MAX_VALUE, false) </pre>
1058
*
1059
* @return A lock object representing the newly-acquired lock
1060
*
1061
* @throws ClosedChannelException
1062
* If this channel is closed
1063
*
1064
* @throws AsynchronousCloseException
1065
* If another thread closes this channel while the invoking
1066
* thread is blocked in this method
1067
*
1068
* @throws FileLockInterruptionException
1069
* If the invoking thread is interrupted while blocked in this
1070
* method
1071
*
1072
* @throws OverlappingFileLockException
1073
* If a lock that overlaps the requested region is already held by
1074
* this Java virtual machine, or if another thread is already
1075
* blocked in this method and is attempting to lock an overlapping
1076
* region of the same file
1077
*
1078
* @throws NonWritableChannelException
1079
* If this channel was not opened for writing
1080
*
1081
* @throws IOException
1082
* If some other I/O error occurs
1083
*
1084
* @see #lock(long,long,boolean)
1085
* @see #tryLock()
1086
* @see #tryLock(long,long,boolean)
1087
*/
1088
public final FileLock lock() throws IOException {
1089
return lock(0L, Long.MAX_VALUE, false);
1090
}
1091
1092
/**
1093
* Attempts to acquire a lock on the given region of this channel's file.
1094
*
1095
* <p> This method does not block. An invocation always returns
1096
* immediately, either having acquired a lock on the requested region or
1097
* having failed to do so. If it fails to acquire a lock because an
1098
* overlapping lock is held by another program then it returns
1099
* {@code null}. If it fails to acquire a lock for any other reason then
1100
* an appropriate exception is thrown.
1101
*
1102
* <p> The region specified by the {@code position} and {@code size}
1103
* parameters need not be contained within, or even overlap, the actual
1104
* underlying file. Lock regions are fixed in size; if a locked region
1105
* initially contains the end of the file and the file grows beyond the
1106
* region then the new portion of the file will not be covered by the lock.
1107
* If a file is expected to grow in size and a lock on the entire file is
1108
* required then a region starting at zero, and no smaller than the
1109
* expected maximum size of the file, should be locked. The zero-argument
1110
* {@link #tryLock()} method simply locks a region of size {@link
1111
* Long#MAX_VALUE}.
1112
*
1113
* <p> Some operating systems do not support shared locks, in which case a
1114
* request for a shared lock is automatically converted into a request for
1115
* an exclusive lock. Whether the newly-acquired lock is shared or
1116
* exclusive may be tested by invoking the resulting lock object's {@link
1117
* FileLock#isShared() isShared} method.
1118
*
1119
* <p> File locks are held on behalf of the entire Java virtual machine.
1120
* They are not suitable for controlling access to a file by multiple
1121
* threads within the same virtual machine. </p>
1122
*
1123
* @param position
1124
* The position at which the locked region is to start; must be
1125
* non-negative
1126
*
1127
* @param size
1128
* The size of the locked region; must be non-negative, and the sum
1129
* {@code position}&nbsp;+&nbsp;{@code size} must be non-negative
1130
*
1131
* @param shared
1132
* {@code true} to request a shared lock,
1133
* {@code false} to request an exclusive lock
1134
*
1135
* @return A lock object representing the newly-acquired lock,
1136
* or {@code null} if the lock could not be acquired
1137
* because another program holds an overlapping lock
1138
*
1139
* @throws IllegalArgumentException
1140
* If the preconditions on the parameters do not hold
1141
*
1142
* @throws ClosedChannelException
1143
* If this channel is closed
1144
*
1145
* @throws OverlappingFileLockException
1146
* If a lock that overlaps the requested region is already held by
1147
* this Java virtual machine, or if another thread is already
1148
* blocked in this method and is attempting to lock an overlapping
1149
* region of the same file
1150
*
1151
* @throws IOException
1152
* If some other I/O error occurs
1153
*
1154
* @see #lock()
1155
* @see #lock(long,long,boolean)
1156
* @see #tryLock()
1157
*/
1158
public abstract FileLock tryLock(long position, long size, boolean shared)
1159
throws IOException;
1160
1161
/**
1162
* Attempts to acquire an exclusive lock on this channel's file.
1163
*
1164
* <p> An invocation of this method of the form {@code fc.tryLock()}
1165
* behaves in exactly the same way as the invocation
1166
*
1167
* <pre>
1168
* fc.{@link #tryLock(long,long,boolean) tryLock}(0L, Long.MAX_VALUE, false) </pre>
1169
*
1170
* @return A lock object representing the newly-acquired lock,
1171
* or {@code null} if the lock could not be acquired
1172
* because another program holds an overlapping lock
1173
*
1174
* @throws ClosedChannelException
1175
* If this channel is closed
1176
*
1177
* @throws OverlappingFileLockException
1178
* If a lock that overlaps the requested region is already held by
1179
* this Java virtual machine, or if another thread is already
1180
* blocked in this method and is attempting to lock an overlapping
1181
* region
1182
*
1183
* @throws IOException
1184
* If some other I/O error occurs
1185
*
1186
* @see #lock()
1187
* @see #lock(long,long,boolean)
1188
* @see #tryLock(long,long,boolean)
1189
*/
1190
public final FileLock tryLock() throws IOException {
1191
return tryLock(0L, Long.MAX_VALUE, false);
1192
}
1193
1194
}
1195
1196