下面列出了怎么用java.nio.file.OpenOption的API类实例代码及写法,或者点击链接到github查看源代码。
private void saveToDisk(byte[] contents, OpenOption openOption) throws IOException {
if (contents == null || contents.length == 0) {
log.warn("Ignored empty byte array");
return;
}
Path path = mirrorProperties.getAddressBookPath();
Path tempPath = path.resolveSibling(path.getFileName() + ".tmp");
Files.write(tempPath, contents, StandardOpenOption.CREATE, StandardOpenOption.WRITE, openOption);
log.info("Saved {}B partial address book update to {}", contents.length, tempPath);
try {
Collection<NodeAddress> nodeAddresses = parse(tempPath);
if (!nodeAddresses.isEmpty()) {
Files.move(tempPath, path, StandardCopyOption.REPLACE_EXISTING);
this.nodeAddresses = nodeAddresses;
log.info("New address book with {} addresses successfully parsed and saved to {}",
nodeAddresses.size(), path);
}
} catch (Exception e) {
log.warn("Unable to parse address book: {}", e.getMessage());
}
}
public PropertyHandler(String propertyfile) {
try {
this.properties = new Properties();
this.properties.load(this.getResourceAsStream("/smc.properties"));
Path configFile = Paths.get(propertyfile);
if (Files.exists(configFile, new LinkOption[0])) {
try {
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(configFile), charset);
String pathToFile = Paths.get(propertyfile).getParent().toString().replace("\\", "/");
content = content.replaceAll("%CONF%", pathToFile);
Files.write(configFile, content.getBytes(charset), new OpenOption[0]);
} finally {
this.properties.load(Files.newInputStream(configFile));
}
}
instance = this;
} catch (Exception var10) {
throw new RuntimeException(var10);
}
}
private static void fchCopy(Path src, Path dst) throws IOException
{
Set<OpenOption> read = new HashSet<>();
read.add(READ);
Set<OpenOption> openwrite = new HashSet<>();
openwrite.add(CREATE_NEW);
openwrite.add(WRITE);
try (FileChannel srcFc = src.getFileSystem()
.provider()
.newFileChannel(src, read);
FileChannel dstFc = dst.getFileSystem()
.provider()
.newFileChannel(dst, openwrite))
{
ByteBuffer bb = ByteBuffer.allocate(8192);
while (srcFc.read(bb) >= 0) {
bb.flip();
dstFc.write(bb);
bb.clear();
}
}
}
/***************************************
* A helper function that opens a file channel for a certain file name and
* open options.
*
* @param sFileName The file name
* @param rMode The open option for the file access mode (e.g.
* READ, WRITE)
* @param rExtraOptions Optional extra file open options
*
* @return The file channel
*/
protected static AsynchronousFileChannel openFileChannel(
String sFileName,
OpenOption rMode,
OpenOption... rExtraOptions)
{
try
{
return AsynchronousFileChannel.open(
new File(sFileName).toPath(),
CollectionUtil.join(rExtraOptions, rMode));
}
catch (IOException e)
{
throw new CoroutineException(e);
}
}
@Override
public void exportTo(final FlowFile flowFile, final Path path, final boolean append) {
validateState(flowFile);
if (flowFile == null || path == null) {
throw new IllegalArgumentException("argument cannot be null");
}
if (!(flowFile instanceof MockFlowFile)) {
throw new IllegalArgumentException("Cannot export a flow file that I did not create");
}
final MockFlowFile mock = (MockFlowFile) flowFile;
final OpenOption mode = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;
try (final OutputStream out = Files.newOutputStream(path, mode)) {
out.write(mock.getData());
} catch (final IOException e) {
throw new FlowFileAccessException(e.toString(), e);
}
}
protected OutputStream getOutputStream(final String path, final boolean append) throws LocalAccessDeniedException {
try {
final Set<OpenOption> options = new HashSet<>();
options.add(StandardOpenOption.WRITE);
if(!this.exists()) {
options.add(StandardOpenOption.CREATE);
}
if(append) {
options.add(StandardOpenOption.APPEND);
}
else {
options.add(StandardOpenOption.TRUNCATE_EXISTING);
}
final FileChannel channel = FileChannel.open(Paths.get(path), options);
return Channels.newOutputStream(channel);
}
catch(RuntimeException | IOException e) {
throw new LocalAccessDeniedException(e.getMessage(), e);
}
}
/**
* Returns a {@code BodyHandler<Path>} that returns a
* {@link BodyProcessor BodyProcessor}<{@link Path}>
* where the download directory is specified, but the filename is
* obtained from the {@code Content-Disposition} response header. The
* {@code Content-Disposition} header must specify the <i>attachment</i> type
* and must also contain a
* <i>filename</i> parameter. If the filename specifies multiple path
* components only the final component is used as the filename (with the
* given directory name). When the {@code HttpResponse} object is
* returned, the body has been completely written to the file and {@link
* #body()} returns a {@code Path} object for the file. The returned {@code Path} is the
* combination of the supplied directory name and the file name supplied
* by the server. If the destination directory does not exist or cannot
* be written to, then the response will fail with an {@link IOException}.
*
* @param directory the directory to store the file in
* @param openOptions open options
* @return a response body handler
*/
public static BodyHandler<Path> asFileDownload(Path directory, OpenOption... openOptions) {
return (status, headers) -> {
String dispoHeader = headers.firstValue("Content-Disposition")
.orElseThrow(() -> unchecked(new IOException("No Content-Disposition")));
if (!dispoHeader.startsWith("attachment;")) {
throw unchecked(new IOException("Unknown Content-Disposition type"));
}
int n = dispoHeader.indexOf("filename=");
if (n == -1) {
throw unchecked(new IOException("Bad Content-Disposition type"));
}
int lastsemi = dispoHeader.lastIndexOf(';');
String disposition;
if (lastsemi < n) {
disposition = dispoHeader.substring(n + 9);
} else {
disposition = dispoHeader.substring(n + 9, lastsemi);
}
Path file = Paths.get(directory.toString(), disposition);
return BodyProcessor.asFile(file, openOptions);
};
}
/**
* Copies the content of a resource to a file.
*
* @param classloader The class loader of the resource.
* @param resourceName The resource name.
* @param destination The destination file.
* @param options Options specifying how the destination file should be opened.
* @return The destination file.
* @throws IOException If an I/O error occurs.
*/
public static Path copyResource(ClassLoader classloader, String resourceName, Path destination, OpenOption... options)
throws IOException {
requireNonNull(resourceName);
requireNonNull(destination);
try (OutputStream out = java.nio.file.Files.newOutputStream(destination, options)) {
copyResource(classloader, resourceName, out);
}
return destination;
}
private void createCsvFile(File directory, CsvFileData csvData, boolean append) throws IOException
{
File file = new File(directory, csvData.getFileName());
boolean fileExists = file.exists();
OpenOption[] openOptions = append ? new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.APPEND }
: new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING };
try (Writer writer = new OutputStreamWriter(Files.newOutputStream(file.toPath(), openOptions),
StandardCharsets.UTF_8);
CSVPrinter printer = append && fileExists ? csvFormat.print(writer)
: csvFormat.withHeader(csvData.getHeader()).print(writer))
{
printer.printRecords(csvData.getData());
}
}
public static OutputStream createOutputStream( Path path, OpenOption... options )
{
try
{
return Files.newOutputStream( path, options );
}
catch( IOException e )
{
throw new RuntimeException( e );
}
}
/**
* Open/creates file, returning FileChannel to access the file
*
* @param pathForWindows
* The path of the file to open/create
* @param pathToCheck
* The path used for permission checks (if security manager)
*/
static FileChannel newFileChannel(String pathForWindows,
String pathToCheck,
Set<? extends OpenOption> options,
long pSecurityDescriptor)
throws WindowsException
{
Flags flags = Flags.toFlags(options);
// default is reading; append => writing
if (!flags.read && !flags.write) {
if (flags.append) {
flags.write = true;
} else {
flags.read = true;
}
}
// validation
if (flags.read && flags.append)
throw new IllegalArgumentException("READ + APPEND not allowed");
if (flags.append && flags.truncateExisting)
throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor);
return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, flags.append, null);
}
/**
* Exercise NullPointerException
*/
public void testNulls() {
Path file = Paths.get("foo");
byte[] bytes = new byte[100];
List<String> lines = Collections.emptyList();
checkNullPointerException(() -> Files.readAllBytes(null));
checkNullPointerException(() -> Files.write(null, bytes));
checkNullPointerException(() -> Files.write(file, (byte[])null));
checkNullPointerException(() -> Files.write(file, bytes, (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, bytes, new OpenOption[] { null } ));
checkNullPointerException(() -> Files.readAllLines(null));
checkNullPointerException(() -> Files.readAllLines(file, (Charset)null));
checkNullPointerException(() -> Files.readAllLines(null, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(null, lines));
checkNullPointerException(() -> Files.write(file, (List<String>)null));
checkNullPointerException(() -> Files.write(file, lines, (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, lines, new OpenOption[] { null } ));
checkNullPointerException(() -> Files.write(null, lines, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(file, null, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(file, lines, (Charset)null));
checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), new OpenOption[] { null } ));
}
@Override
public SeekableByteChannel newByteChannel(Path file,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
throws IOException
{
triggerEx(file, "newByteChannel");
return Files.newByteChannel(unwrap(file), options, attrs);
}
/**
* Open/creates file, returning FileChannel to access the file
*
* @param pathForWindows
* The path of the file to open/create
* @param pathToCheck
* The path used for permission checks (if security manager)
*/
static FileChannel newFileChannel(String pathForWindows,
String pathToCheck,
Set<? extends OpenOption> options,
long pSecurityDescriptor)
throws WindowsException
{
Flags flags = Flags.toFlags(options);
// default is reading; append => writing
if (!flags.read && !flags.write) {
if (flags.append) {
flags.write = true;
} else {
flags.read = true;
}
}
// validation
if (flags.read && flags.append)
throw new IllegalArgumentException("READ + APPEND not allowed");
if (flags.append && flags.truncateExisting)
throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor);
return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, flags.append, null);
}
/**
* Exercise NullPointerException
*/
public void testNulls() {
Path file = Paths.get("foo");
byte[] bytes = new byte[100];
List<String> lines = Collections.emptyList();
checkNullPointerException(() -> Files.readAllBytes(null));
checkNullPointerException(() -> Files.write(null, bytes));
checkNullPointerException(() -> Files.write(file, (byte[])null));
checkNullPointerException(() -> Files.write(file, bytes, (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, bytes, new OpenOption[] { null } ));
checkNullPointerException(() -> Files.readAllLines(null));
checkNullPointerException(() -> Files.readAllLines(file, (Charset)null));
checkNullPointerException(() -> Files.readAllLines(null, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(null, lines));
checkNullPointerException(() -> Files.write(file, (List<String>)null));
checkNullPointerException(() -> Files.write(file, lines, (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, lines, new OpenOption[] { null } ));
checkNullPointerException(() -> Files.write(null, lines, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(file, null, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(file, lines, (Charset)null));
checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), new OpenOption[] { null } ));
}
@Override
public SeekableByteChannel newByteChannel(Path file,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
throws IOException
{
triggerEx(file, "newByteChannel");
return Files.newByteChannel(unwrap(file), options, attrs);
}
/**
* Open/creates file, returning FileChannel to access the file
*
* @param pathForWindows
* The path of the file to open/create
* @param pathToCheck
* The path used for permission checks (if security manager)
*/
static FileChannel newFileChannel(String pathForWindows,
String pathToCheck,
Set<? extends OpenOption> options,
long pSecurityDescriptor)
throws WindowsException
{
Flags flags = Flags.toFlags(options);
// default is reading; append => writing
if (!flags.read && !flags.write) {
if (flags.append) {
flags.write = true;
} else {
flags.read = true;
}
}
// validation
if (flags.read && flags.append)
throw new IllegalArgumentException("READ + APPEND not allowed");
if (flags.append && flags.truncateExisting)
throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor);
return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, flags.append, null);
}
/**
* Exercise NullPointerException
*/
public void testNulls() {
Path file = Paths.get("foo");
byte[] bytes = new byte[100];
List<String> lines = Collections.emptyList();
checkNullPointerException(() -> Files.readAllBytes(null));
checkNullPointerException(() -> Files.write(null, bytes));
checkNullPointerException(() -> Files.write(file, (byte[])null));
checkNullPointerException(() -> Files.write(file, bytes, (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, bytes, new OpenOption[] { null } ));
checkNullPointerException(() -> Files.readAllLines(null));
checkNullPointerException(() -> Files.readAllLines(file, (Charset)null));
checkNullPointerException(() -> Files.readAllLines(null, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(null, lines));
checkNullPointerException(() -> Files.write(file, (List<String>)null));
checkNullPointerException(() -> Files.write(file, lines, (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, lines, new OpenOption[] { null } ));
checkNullPointerException(() -> Files.write(null, lines, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(file, null, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(file, lines, (Charset)null));
checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), new OpenOption[] { null } ));
}
@Override
public SeekableByteChannel newByteChannel(Path file,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
throws IOException
{
triggerEx(file, "newByteChannel");
return Files.newByteChannel(unwrap(file), options, attrs);
}
/**
* Copies the content of a resource to a file.
*
* @param resourceName The resource name.
* @param destination The destination file.
* @param options Options specifying how the destination file should be opened.
* @return The destination file.
* @throws IOException If an I/O error occurs.
*/
public static Path copyResource(String resourceName, Path destination, OpenOption... options) throws IOException {
requireNonNull(resourceName);
requireNonNull(destination);
try (OutputStream out = java.nio.file.Files.newOutputStream(destination, options)) {
copyResource(resourceName, out);
}
return destination;
}
@Override
public void run(final RunNotifier notifier) {
super.run(notifier);
if (delta != 0)
return;
try {
final String className = getTestClass().getName();
final File manifestFile = getManifestFile();
manifestFile.getParentFile().mkdirs();
final Path path = manifestFile.toPath();
final OpenOption openOption;
if (Files.exists(path)) {
// Check if the test class name is mentioned in the manifest
try (final BufferedReader reader = new BufferedReader(new FileReader(manifestFile))) {
String line;
while ((line = reader.readLine()) != null)
if (line.equals(className))
return;
}
openOption = StandardOpenOption.APPEND;
}
else {
openOption = StandardOpenOption.CREATE;
}
// Add the test class name to the manifest
Files.write(path, (className + "\n").getBytes(), openOption);
}
catch (final IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public SeekableByteChannel newByteChannel(Path file,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
throws IOException
{
triggerEx(file, "newByteChannel");
return Files.newByteChannel(unwrap(file), options, attrs);
}
@Test
public void newFileChannel() throws IOException
{
final Path path = mock(Path.class);
final Set<OpenOption> options = new HashSet<>();
provider.newFileChannel(path, options);
verify(delegate).newFileChannel(path, options);
}
@Test
public void newAsynchronousFileChannel() throws IOException {
final Path path = mock(Path.class);
final Set<OpenOption> options = new HashSet<>();
final ExecutorService executorService = mock(ExecutorService.class);
provider.newAsynchronousFileChannel(path, options, executorService);
verify(delegate).newAsynchronousFileChannel(path, options, executorService);
}
/**
* Open/creates file, returning FileChannel to access the file
*
* @param pathForWindows
* The path of the file to open/create
* @param pathToCheck
* The path used for permission checks (if security manager)
*/
static FileChannel newFileChannel(String pathForWindows,
String pathToCheck,
Set<? extends OpenOption> options,
long pSecurityDescriptor)
throws WindowsException
{
Flags flags = Flags.toFlags(options);
// default is reading; append => writing
if (!flags.read && !flags.write) {
if (flags.append) {
flags.write = true;
} else {
flags.read = true;
}
}
// validation
if (flags.read && flags.append)
throw new IllegalArgumentException("READ + APPEND not allowed");
if (flags.append && flags.truncateExisting)
throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor);
return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, flags.append, null);
}
/**
* Exercise NullPointerException
*/
public void testNulls() {
Path file = Paths.get("foo");
byte[] bytes = new byte[100];
List<String> lines = Collections.emptyList();
checkNullPointerException(() -> Files.readAllBytes(null));
checkNullPointerException(() -> Files.write(null, bytes));
checkNullPointerException(() -> Files.write(file, (byte[])null));
checkNullPointerException(() -> Files.write(file, bytes, (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, bytes, new OpenOption[] { null } ));
checkNullPointerException(() -> Files.readAllLines(null));
checkNullPointerException(() -> Files.readAllLines(file, (Charset)null));
checkNullPointerException(() -> Files.readAllLines(null, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(null, lines));
checkNullPointerException(() -> Files.write(file, (List<String>)null));
checkNullPointerException(() -> Files.write(file, lines, (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, lines, new OpenOption[] { null } ));
checkNullPointerException(() -> Files.write(null, lines, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(file, null, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(file, lines, (Charset)null));
checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), new OpenOption[] { null } ));
}
@Override
public SeekableByteChannel newByteChannel(Path file,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
throws IOException
{
triggerEx(file, "newByteChannel");
return Files.newByteChannel(unwrap(file), options, attrs);
}
/** Helper to read a file into a byte buffer. The buffer is flipped before returned. */
public static ByteBuffer readFile(Path path, OpenOption... options) {
try (SeekableByteChannel file = Files.newByteChannel(path, options)) {
ByteBuffer buf = ByteBuffer.allocateDirect((int) file.size());
file.read(buf);
if (buf.hasRemaining()) throw new IOException("Failed reading entire file");
buf.flip();
return buf;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static boolean writeToFile(String filename, byte[] contents, boolean overwrite) {
// default Files behavior is to overwrite. If we specify no overwrite then CREATE_NEW fails
// if the file exist. This operation is atomic.
OpenOption[] options = overwrite
? new OpenOption[]{} : new OpenOption[]{StandardOpenOption.CREATE_NEW};
try {
Files.write(new File(filename).toPath(), contents, options);
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to write content to file. ", e);
return false;
}
return true;
}
/**
* Exercise NullPointerException
*/
public void testNulls() {
Path file = Paths.get("foo");
byte[] bytes = new byte[100];
List<String> lines = Collections.emptyList();
checkNullPointerException(() -> Files.readAllBytes(null));
checkNullPointerException(() -> Files.write(null, bytes));
checkNullPointerException(() -> Files.write(file, (byte[])null));
checkNullPointerException(() -> Files.write(file, bytes, (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, bytes, new OpenOption[] { null } ));
checkNullPointerException(() -> Files.readAllLines(null));
checkNullPointerException(() -> Files.readAllLines(file, (Charset)null));
checkNullPointerException(() -> Files.readAllLines(null, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(null, lines));
checkNullPointerException(() -> Files.write(file, (List<String>)null));
checkNullPointerException(() -> Files.write(file, lines, (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, lines, new OpenOption[] { null } ));
checkNullPointerException(() -> Files.write(null, lines, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(file, null, Charset.defaultCharset()));
checkNullPointerException(() -> Files.write(file, lines, (Charset)null));
checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), (OpenOption[])null));
checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), new OpenOption[] { null } ));
}