下面列出了java.nio.file.StandardOpenOption#CREATE_NEW 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public IndexOutput createTempOutput(String prefix, String suffix, IOContext context) throws IOException {
ensureOpen();
maybeDeletePendingFiles();
while (true) {
try {
String name = getTempFileName(prefix, suffix, nextTempFileCounter.getAndIncrement());
if (pendingDeletes.contains(name)) {
continue;
}
return new FSIndexOutput(name,
StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
} catch (FileAlreadyExistsException faee) {
// Retry with next incremented name
}
}
}
public FileChannel getSaveFileChannel(String fileName) {
FileDialog fd = new FileDialog(shlSimpleChatExample, SWT.SAVE);
fd.setText("Choose a file for the incoming file transfer");
fd.setFileName(fileName);
String selected = fd.open();
Path path = FileSystems.getDefault().getPath(selected);
OpenOption[] read = { StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW };
try {
System.out.println("File will be saved to: "+path);
FileChannel fileChannel = FileChannel.open(path, read);
return fileChannel;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
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;
}
static OpenOptions forNewOutputStream(Collection<? extends OpenOption> options) {
if (options.isEmpty()) {
// CREATE, TRUNCATE_EXISTING and WRITE, i.e. create, not createNew, and not append
return new OpenOptions(false, true, false, true, false, false, Collections.<OpenOption>emptySet());
}
boolean append = false;
boolean truncateExisting = false;
boolean create = false;
boolean createNew = false;
boolean deleteOnClose = false;
for (OpenOption option : options) {
if (option == StandardOpenOption.APPEND) {
append = true;
} else if (option == StandardOpenOption.TRUNCATE_EXISTING) {
truncateExisting = true;
} else if (option == StandardOpenOption.CREATE) {
create = true;
} else if (option == StandardOpenOption.CREATE_NEW) {
createNew = true;
} else if (option == StandardOpenOption.DELETE_ON_CLOSE) {
deleteOnClose = true;
} else if (option != StandardOpenOption.WRITE && !isIgnoredOpenOption(option)) {
throw Messages.fileSystemProvider().unsupportedOpenOption(option);
}
}
// append and truncateExisting contradict each other
if (append && truncateExisting) {
throw Messages.fileSystemProvider().illegalOpenOptionCombination(options);
}
return new OpenOptions(false, true, append, create, createNew, deleteOnClose, options);
}
@Test
public void testNewOutputStreamExistingCreateNew() throws IOException {
addDirectory("/foo");
addFile("/foo/bar");
OpenOption[] options = { StandardOpenOption.CREATE_NEW };
FileAlreadyExistsException exception = assertThrows(FileAlreadyExistsException.class,
() -> fileSystem.newOutputStream(createPath("/foo/bar"), options));
assertEquals("/foo/bar", exception.getFile());
// verify that the file system can be used after closing the stream
assertDoesNotThrow(() -> fileSystem.checkAccess(createPath("/foo/bar")));
assertTrue(Files.isDirectory(getPath("/foo")));
assertTrue(Files.isRegularFile(getPath("/foo/bar")));
}
@Test
public void testNewOutputStreamNonExistingCreateNew() throws IOException {
addDirectory("/foo");
OpenOption[] options = { StandardOpenOption.CREATE_NEW };
try (OutputStream input = fileSystem.newOutputStream(createPath("/foo/bar"), options)) {
// don't do anything with the stream, there's a separate test for that
} finally {
assertTrue(Files.isDirectory(getPath("/foo")));
assertTrue(Files.isRegularFile(getPath("/foo/bar")));
}
}
@Test
public void testNewOutputStreamNonExistingCreateNewDeleteOnClose() throws IOException {
addDirectory("/foo");
OpenOption[] options = { StandardOpenOption.CREATE_NEW, StandardOpenOption.DELETE_ON_CLOSE };
try (OutputStream input = fileSystem.newOutputStream(createPath("/foo/bar"), options)) {
// don't do anything with the stream, there's a separate test for that
// we can't check here that /foo/bar exists, because it will only be stored in the file system once the stream is closed
} finally {
assertTrue(Files.isDirectory(getPath("/foo")));
assertFalse(Files.exists(getPath("/foo/bar")));
}
}
@Nullable
private BufferedWriter initWriter() {
try {
StandardOpenOption openOption =
Files.exists(filePath)
? StandardOpenOption.TRUNCATE_EXISTING
: StandardOpenOption.CREATE_NEW;
return Files.newBufferedWriter(filePath, StandardCharsets.UTF_8, openOption);
} catch (IOException e) {
failed = true;
logger.atSevere().withCause(e).log(
"Could not open file: %s. Redirecting will be disabled.", filePath);
}
return null;
}
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;
}
public FSIndexOutput(String name) throws IOException {
this(name, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
}
static OpenOptions forNewByteChannel(Set<? extends OpenOption> options) {
boolean read = false;
boolean write = false;
boolean append = false;
boolean truncateExisting = false;
boolean create = false;
boolean createNew = false;
boolean deleteOnClose = false;
for (OpenOption option : options) {
if (option == StandardOpenOption.READ) {
read = true;
} else if (option == StandardOpenOption.WRITE) {
write = true;
} else if (option == StandardOpenOption.APPEND) {
append = true;
} else if (option == StandardOpenOption.TRUNCATE_EXISTING) {
truncateExisting = true;
} else if (option == StandardOpenOption.CREATE) {
create = true;
} else if (option == StandardOpenOption.CREATE_NEW) {
createNew = true;
} else if (option == StandardOpenOption.DELETE_ON_CLOSE) {
deleteOnClose = true;
} else if (!isIgnoredOpenOption(option)) {
throw Messages.fileSystemProvider().unsupportedOpenOption(option);
}
}
// as per Files.newByteChannel, if none of these options is given, default to read
if (!read && !write && !append) {
read = true;
}
// read contradicts with write, append, create and createNew; TRUNCATE_EXISTING is ignored in combination with READ
if (read && (write || append || create || createNew)) {
throw Messages.fileSystemProvider().illegalOpenOptionCombination(options);
}
// append and truncateExisting contract each other
if (append && truncateExisting) {
throw Messages.fileSystemProvider().illegalOpenOptionCombination(options);
}
// read and write contract each other; read and append contract each other; append and truncateExisting contract each other
if ((read && write) || (read && append) || (append && truncateExisting)) {
throw Messages.fileSystemProvider().illegalOpenOptionCombination(options);
}
return new OpenOptions(read, write, append, create, createNew, deleteOnClose, options);
}