本文整理匯總了Java中java.nio.file.FileAlreadyExistsException類的典型用法代碼示例。如果您正苦於以下問題:Java FileAlreadyExistsException類的具體用法?Java FileAlreadyExistsException怎麽用?Java FileAlreadyExistsException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
FileAlreadyExistsException類屬於java.nio.file包,在下文中一共展示了FileAlreadyExistsException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: ensureDirectoryExists
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
/**
* Ensures configured directory {@code path} exists.
* @throws IOException if {@code path} exists, but is not a directory, not accessible, or broken symbolic link.
*/
static void ensureDirectoryExists(Path path) throws IOException {
// this isn't atomic, but neither is createDirectories.
if (Files.isDirectory(path)) {
// verify access, following links (throws exception if something is wrong)
// we only check READ as a sanity test
path.getFileSystem().provider().checkAccess(path.toRealPath(), AccessMode.READ);
} else {
// doesn't exist, or not a directory
try {
Files.createDirectories(path);
} catch (FileAlreadyExistsException e) {
// convert optional specific exception so the context is clear
IOException e2 = new NotDirectoryException(path.toString());
e2.addSuppressed(e);
throw e2;
}
}
}
示例2: testRecoverWithUnbackedNextGenInIllegalState
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
public void testRecoverWithUnbackedNextGenInIllegalState() throws IOException {
translog.add(new Translog.Index("test", "" + 0, Integer.toString(0).getBytes(Charset.forName("UTF-8"))));
Translog.TranslogGeneration translogGeneration = translog.getGeneration();
translog.close();
TranslogConfig config = translog.getConfig();
Path ckp = config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME);
Checkpoint read = Checkpoint.read(ckp);
// don't copy the new file
Files.createFile(config.getTranslogPath().resolve("translog-" + (read.generation + 1) + ".tlog"));
try {
Translog tlog = new Translog(config, translogGeneration, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO);
fail("file already exists?");
} catch (TranslogException ex) {
// all is well
assertEquals(ex.getMessage(), "failed to create new translog file");
assertEquals(ex.getCause().getClass(), FileAlreadyExistsException.class);
}
}
示例3: testFileSystemExceptions
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
public void testFileSystemExceptions() throws IOException {
for (FileSystemException ex : Arrays.asList(new FileSystemException("a", "b", "c"),
new NoSuchFileException("a", "b", "c"),
new NotDirectoryException("a"),
new DirectoryNotEmptyException("a"),
new AtomicMoveNotSupportedException("a", "b", "c"),
new FileAlreadyExistsException("a", "b", "c"),
new AccessDeniedException("a", "b", "c"),
new FileSystemLoopException("a"))) {
FileSystemException serialize = serialize(ex);
assertEquals(serialize.getClass(), ex.getClass());
assertEquals("a", serialize.getFile());
if (serialize.getClass() == NotDirectoryException.class ||
serialize.getClass() == FileSystemLoopException.class ||
serialize.getClass() == DirectoryNotEmptyException.class) {
assertNull(serialize.getOtherFile());
assertNull(serialize.getReason());
} else {
assertEquals(serialize.getClass().toString(), "b", serialize.getOtherFile());
assertEquals(serialize.getClass().toString(), "c", serialize.getReason());
}
}
}
示例4: SeekableSMBByteChannel
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
/**
* Constructor for {@link SeekableSMBByteChannel}
*
* @param file The {@link SmbFile} instance that should be opened.
* @param write Flag that indicates, whether write access is requested.
* @param create Flag that indicates, whether file should be created.
* @param create_new Flag that indicates, whether file should be created. If it is set to true, operation will fail if file exists!
* @param truncate Flag that indicates, whether file should be truncated to length 0 when being opened.
* @param append Flag that indicates, whether data should be appended.
* @throws IOException If something goes wrong when accessing the file.
*/
SeekableSMBByteChannel(SmbFile file, boolean write, boolean create, boolean create_new, boolean truncate, boolean append) throws IOException {
/* Tries to create a new file, if so specified. */
if (create || create_new) {
if (file.exists()) {
if (create_new) throw new FileAlreadyExistsException("The specified file '" + file.getPath() + "' does already exist!");
} else {
file.createNewFile();
}
}
/* Opens the file with either read only or write access. */
if (write) {
file.setReadWrite();
this.random = new SmbRandomAccessFile(file, "rw");
if (truncate) this.random.setLength(0);
if (append) this.random.seek(this.random.length());
} else {
file.setReadOnly();
this.random = new SmbRandomAccessFile(file, "r");
}
}
示例5: createNewFile
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
/**
* Creates a new, empty file similar to its superclass implementation.
* Note that this method doesn't create archive files because archive
* files are virtual directories, not files!
*
* @see #mkdir
*/
@Override
@FsAssertion(consistent=YES, isolated=NO)
public boolean createNewFile() throws IOException {
if (null != innerArchive) {
try {
innerArchive.getController().make(
getAccessPreferences().set(EXCLUSIVE), getNodeName(),
FILE,
null);
return true;
} catch (final FileAlreadyExistsException ex) {
return false;
}
}
return file.createNewFile();
}
示例6: touch
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
/**
* Like the unix command of the same name, creates an empty file or updates the last modified
* timestamp of the existing file at the given path to the current system time.
*/
public static void touch(Path path) throws IOException {
checkNotNull(path);
try {
Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()));
} catch (NoSuchFileException e) {
try {
Files.createFile(path);
} catch (FileAlreadyExistsException ignore) {
// The file didn't exist when we called setLastModifiedTime, but it did when we called
// createFile, so something else created the file in between. The end result is
// what we wanted: a new file that probably has its last modified time set to approximately
// now. Or it could have an arbitrary last modified time set by the creator, but that's no
// different than if another process set its last modified time to something else after we
// created it here.
}
}
}
示例7: mkSymlink
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
public void mkSymlink(String symlinkName, String symlinkTarget) throws StorageAdapterException {
try {
File link = new File(symlinkName);
File target = new File(symlinkTarget);
mkParentDirs(link); // make sure directory containing the link exists
Files.createSymbolicLink(link.toPath(), target.toPath());
} catch (Exception e) {
String errMsg = e.getMessage();
if (e instanceof FileAlreadyExistsException) {
errMsg = "the file already exists";
}
errMsg = String.format("Error creating symlink %s to target %s: %s", symlinkName,
symlinkTarget, errMsg);
LOG.log(Level.WARNING, errMsg, e);
throw new StorageAdapterException(errMsg, e);
}
}
示例8: exportASM
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
private void exportASM(String asmName, File destination, boolean overwriteAllowed)
throws FileAlreadyExistsException, DiskOperationFailedException
{
if (destination == null)
throw new IllegalStateException("Failed to create file object");
else if (destination.exists() && !overwriteAllowed)
throw new FileAlreadyExistsException(destination.getAbsolutePath());
ASMFile asmFile = getASMByName(asmName);
ensureExists(destination);
try (PrintWriter writer = new PrintWriter(destination))
{
writer.print(asmFile.getContent());
}
catch (IOException exception)
{
throw new DiskOperationFailedException(exception);
}
}
示例9: writeList
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
private void writeList() throws IOException, URISyntaxException {
IgnoreList list = new IgnoreList();
boolean isWhite = btnIsWhite.getSelection();
list.setShow(!isWhite);
for (IgnoredObject rule : listEditor.getList()){
rule.setShow(isWhite);
list.add(rule);
}
byte[] out = list.getListCode().getBytes(StandardCharsets.UTF_8);
Path listFile = InternalIgnoreList.getInternalIgnoreFile();
if (listFile != null) {
try {
Files.createDirectories(listFile.getParent());
} catch (FileAlreadyExistsException ex) {
// no action
}
Files.write(listFile, out, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
InternalIgnoreList.notifyListeners(list);
}
}
示例10: initZipLogFile
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
private void initZipLogFile(final Cmd cmd) throws IOException {
// init log directory
try {
Files.createDirectories(DEFAULT_LOG_PATH);
} catch (FileAlreadyExistsException ignore) {
LOGGER.warn("Log path %s already exist", DEFAULT_LOG_PATH);
}
// init zipped log file for tmp
Path stdoutPath = Paths.get(DEFAULT_LOG_PATH.toString(), getLogFileName(cmd, Log.Type.STDOUT, true));
Files.deleteIfExists(stdoutPath);
stdoutLogPath = Files.createFile(stdoutPath);
// init zip stream for stdout log
stdoutLogStream = new FileOutputStream(stdoutLogPath.toFile());
stdoutLogZipStream = new ZipOutputStream(stdoutLogStream);
ZipEntry outEntry = new ZipEntry(cmd.getId() + ".out");
stdoutLogZipStream.putNextEntry(outEntry);
}
示例11: commitSomething
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
private void commitSomething(Path path) {
try (Git git = Git.open(path.toFile())) {
Path emptyFilePath = Paths.get(path.toString(), EMPTY_FILE);
try {
Files.createFile(emptyFilePath);
} catch (FileAlreadyExistsException ignore) {
}
git.add()
.addFilepattern(".")
.call();
git.commit()
.setMessage("add test branch")
.call();
} catch (Throwable e) {
LOGGER.error("Method: commitSomething Exception", e);
}
}
示例12: createDirectory
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
/**
* 創建目錄
*
* @param descDirName 目錄名,包含路徑
* @return 如果創建成功 ,則返回true,否則返回false
* @throws IOException the io exception
*/
public static boolean createDirectory(String descDirName) throws IOException {
String descDirNames = descDirName;
if (!descDirNames.endsWith(File.separator)) {
descDirNames = descDirNames + File.separator;
}
File descDir = new File(descDirNames);
if (descDir.exists()) {
throw new FileAlreadyExistsException(String.format("目錄 %s 已存在!", descDirNames));
}
// 創建目錄
if (descDir.mkdirs()) {
LOGGER.debug("目錄 {} 創建成功!", descDirNames);
return true;
} else {
LOGGER.debug("目錄 {} 創建失敗!", descDirNames);
return false;
}
}
示例13: decompress
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
public static File decompress(File inputFile) throws IOException {
if (!inputFile.exists() || !inputFile.canRead() || !inputFile.getName().endsWith(".bz2")) {
throw new IOException("Cannot read file " + inputFile.getPath());
}
File outputFile = new File(inputFile.toString().substring(0, inputFile.toString().length() - 4));
if (outputFile.exists()) {
throw new FileAlreadyExistsException(outputFile.toString());
}
try (InputStream fileInputStream = new BufferedInputStream(new FileInputStream(inputFile));
BZip2InputStream inputStream = new BZip2InputStream(fileInputStream, false);
OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(outputFile), 524288)) {
byte[] decoded = new byte[524288];
int bytesRead;
while ((bytesRead = inputStream.read(decoded)) != -1) {
fileOutputStream.write(decoded, 0, bytesRead);
}
}
return outputFile;
}
示例14: determineCloudMethodForCopyOrMoveOperations
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
protected CloudMethod determineCloudMethodForCopyOrMoveOperations(
String operationName, CloudPath source, Path target, Set<CopyOption> options) throws IOException {
// Don't copy a file to itself
if (source.equals(target)) {
throw new FileAlreadyExistsException("Cannot " + operationName + " a path to itself from '" + source.toAbsolutePath() +
"' -> '" + target.toAbsolutePath() + "'");
}
// Check if target exists and we are allowed to copy
if (Files.exists(target) && !options.contains(StandardCopyOption.REPLACE_EXISTING)) {
throw new FileAlreadyExistsException("Cannot copy from " + source.toAbsolutePath() +
" to " + target.toAbsolutePath() + ", the file already exists and file replace was not specified");
}
// Check if we can try a JClouds copy or we have to use the filesystem
if (target instanceof CloudPath) {
// Work out if we are using the same cloud settings - if we are then we can use a direct copy
CloudPath cloudPathTarget = (CloudPath)target;
if (source.getFileSystem().getCloudHostConfiguration().canOptimiseOperationsFor(cloudPathTarget)) {
return CloudMethod.CLOUD_OPTIMISED;
}
}
return CloudMethod.LOCAL_FILESYSTEM_FALLBACK;
}
開發者ID:brdara,項目名稱:java-cloud-filesystem-provider,代碼行數:26,代碼來源:DefaultCloudFileSystemImplementation.java
示例15: testCreateDirectoryFailsIfTheDirectoryAlreadyExists
import java.nio.file.FileAlreadyExistsException; //導入依賴的package包/類
@Test
public void testCreateDirectoryFailsIfTheDirectoryAlreadyExists() throws IOException {
String pathName = "content/cloud-dir";
CloudPath cloudPath = new CloudPath(containerPath, pathName);
// Create the parent dir and dir
createDirectory(cloudPath.getParent());
createDirectory(cloudPath);
assertDirectoryExists(cloudPath);
// Now issue another create
try {
impl.createDirectory(blobStoreContext, cloudPath);
Assert.fail("Expected an exception to be thrown");
} catch (FileAlreadyExistsException e) {
// OK
}
}
開發者ID:brdara,項目名稱:java-cloud-filesystem-provider,代碼行數:19,代碼來源:DefaultCloudFileSystemImplementationIntegrationTest.java