Java 类java.nio.file.FileAlreadyExistsException 实例源码

项目:elasticsearch_my    文件:Security.java   
/**
 * 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;
        }
    }
}
项目:elasticsearch_my    文件:TranslogTests.java   
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);
    }
}
项目:elasticsearch_my    文件:ExceptionSerializationTests.java   
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());
        }
    }
}
项目:smb-nio    文件:SeekableSMBByteChannel.java   
/**
 * 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");
    }
}
项目:truevfs    文件:TFile.java   
/**
 * 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();
}
项目:guava-mock    文件:MoreFiles.java   
/**
 * 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.
    }
  }
}
项目:Open-DM    文件:FileSystemAdapter.java   
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);
    }
}
项目:WebPLP    文件:ProjectManager.java   
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);
    }
}
项目:Elasticsearch    文件:Security.java   
/**
 * 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;
        }
    }
}
项目:pgcodekeeper    文件:IgnoredObjectsPrefPage.java   
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);
    }
}
项目:flow-platform    文件:LogEventHandler.java   
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);
}
项目:flow-platform    文件:PluginServiceImpl.java   
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);
    }
}
项目:angit    文件:FileHelper.java   
/**
 * 创建目录
 *
 * @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;
    }

}
项目:googles-monorepo-demo    文件:MoreFiles.java   
/**
 * 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.
    }
  }
}
项目:ugc-bot-redux    文件:BZip2Decompressor.java   
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;
}
项目:java-cloud-filesystem-provider    文件:DefaultCloudFileSystemImplementation.java   
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;
}
项目:java-cloud-filesystem-provider    文件:DefaultCloudFileSystemImplementationIntegrationTest.java   
@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
    }
}
项目:java-cloud-filesystem-provider    文件:DefaultCloudFileSystemImplementationIntegrationTest.java   
@Test
public void testDefaultCopyWillFailIfTheTargetExistsAndReplaceExistingCopyOptionIsNotUsed() throws IOException {
    String originalContent = "This is my content";
    String testFileName = "cloud-file-channel-test.txt";
    CloudPath testFilePath = new CloudPath(containerPath, testFileName);
    createRawContent(testFileName, BlobAccess.PUBLIC_READ, originalContent.getBytes("UTF-8"));
    assertFileExists(testFilePath);

    String targetFileName = "target-copy.txt";
    CloudPath targetFilePath = new CloudPath(containerPath, targetFileName);
    createRawContent(targetFileName, BlobAccess.PRIVATE, originalContent.getBytes("UTF-8"));
    assertFileExists(targetFilePath);

    try {
        impl.copy(blobStoreContext, testFilePath, targetFilePath, Sets.newHashSet(StandardCopyOption.COPY_ATTRIBUTES));
        Assert.fail("Did not expect to be able to copy");
    } catch (FileAlreadyExistsException e) {
        // OK
    }
}
项目:java-cloud-filesystem-provider    文件:DefaultCloudFileSystemImplementationIntegrationTest.java   
public void testLocalFilesystemCopyWillFailIfTheTargetExistsAndReplaceExistingCopyOptionIsNotUsed() throws IOException {
    String originalContent = "This is my content";
    String testFileName = "cloud-file-channel-test.txt";
    CloudPath testFilePath = new CloudPath(containerPath, testFileName);
    createRawContent(testFileName, BlobAccess.PUBLIC_READ, originalContent.getBytes("UTF-8"));

    String targetFileName = "target-copy.txt";
    CloudPath targetFilePath = new CloudPath(containerPath, targetFileName);
    createRawContent(targetFileName, BlobAccess.PRIVATE, originalContent.getBytes("UTF-8"));

    try {
        impl.copyUsingLocalFilesystem(blobStoreContext, testFilePath, targetFilePath,
                Sets.newHashSet(StandardCopyOption.COPY_ATTRIBUTES));
        Assert.fail("Did not expect to be able to copy");
    } catch (FileAlreadyExistsException e) {
        // OK
    }
}
项目:java-cloud-filesystem-provider    文件:DefaultCloudFileSystemImplementationTest.java   
@Test
public void testCreateDirectoryFailsIfThePathExists() throws IOException {
    CloudPath path = context.mock(CloudPath.class, "path");
    BlobStoreContext blobStoreContext = context.mock(BlobStoreContext.class);

    context.checking(new Expectations() {{
        allowing(path).exists();
        will(returnValue(true));

        allowing(path).toAbsolutePath();
        will(returnValue(path));
    }});

    try {
        impl.createDirectory(blobStoreContext, path, new FileAttribute[0]);
        Assert.fail("Did not expect to be able to create the directory when path exists");
    } catch (FileAlreadyExistsException e) {
        // OK
    }
}
项目:java-cloud-filesystem-provider    文件:CloudFileChannelIntegrationTest.java   
@Test
public void testCreateCloudFileChannelForCreatNewFailsIfTheFileExists() throws IOException {
    String pathName = "content/cloud-file-channel-test.txt";
    String originalContent = "This is my content";
    createRawContent(pathName, originalContent.getBytes("UTF-8"));
    CloudPath cloudPath = context.mock(CloudPath.class);

    context.checking(new Expectations() {{
        allowing(cloudPath).getContainerName();
        will(returnValue(CONTAINER_NAME));

        allowing(cloudPath).getPathName();
        will(returnValue(pathName));

        allowing(cloudPath).exists();
        will(returnValue(true));
    }});

    try {
        CloudFileChannel channel = new CloudFileChannel(blobStoreContext, cloudPath, EnumSet.of(StandardOpenOption.CREATE_NEW));
        channel.close();
        Assert.fail("Opening a channel to an existing file with the create new option should fail");
    } catch (FileAlreadyExistsException e) {
        // OK
    }       
}
项目:robozonky    文件:KeyStoreHandler.java   
/**
 * Create brand new key store protected by a given password, and store it in a file.
 * @param keyStoreFile The file where the key store should be.
 * @param password Password to protect the key store.
 * @return Freshly instantiated key store, in a newly created file.
 * @throws IOException If file already exists or there is a problem writing the file.
 * @throws KeyStoreException If something's happened to the key store.
 */
public static KeyStoreHandler create(final File keyStoreFile, final char... password)
        throws IOException, KeyStoreException {
    if (keyStoreFile == null) {
        throw new FileNotFoundException(null);
    } else if (keyStoreFile.exists()) {
        throw new FileAlreadyExistsException(keyStoreFile.getAbsolutePath());
    }
    final KeyStore ks = KeyStore.getInstance(KeyStoreHandler.KEYSTORE_TYPE);
    // get user password and file input stream
    try {
        ks.load(null, password);
    } catch (final Exception ex) {
        throw new IllegalStateException("Should not happen.", ex);
    }
    // store the newly created key store
    final SecretKeyFactory skf = KeyStoreHandler.getSecretKeyFactory();
    final KeyStoreHandler ksh = new KeyStoreHandler(ks, password, keyStoreFile, skf);
    ksh.save();
    return ksh;
}
项目:AutoRename    文件:SeasonManager.java   
@Override
protected boolean rename(File file, String destination) {
    // TODO Auto-generated method stub
    File file2 = FileUtils.getFile(destination, this.getNewName(file));
    try {
        FileUtils.moveDirectory(file, file2);
        this.observed = file2;
        this.propertyFile = new File(file2, "sdata.properties");
        return true;
    } catch (FileAlreadyExistsException e1){
        e1.printStackTrace();
        JOptionPane.showMessageDialog(null, file2.getAbsolutePath() + " already exists.", "Error", JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        new Catcher(e);
    }
    return false;
}
项目:AutoRename    文件:SerieManager.java   
@Override
protected boolean rename(File file, String destination) {
    // TODO Auto-generated method stub
    File file2 = FileUtils.getFile(destination, this.getNewName(file));
    try {
        FileUtils.moveDirectory(file, file2);
        this.observed = file2;
        return true;
    } catch (FileAlreadyExistsException e1){
        e1.printStackTrace();
        JOptionPane.showMessageDialog(null, file2.getAbsolutePath() + " already exists.", "Error", JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        new Catcher(e);
    }
    return false;
}
项目:AutoRename    文件:EpisodeManager.java   
@Override
public boolean rename(File file, String destination) {
    // TODO Auto-generated method stub
    if(this.resolution == null){
        this.resolution = this.getResolution(file);
    }

    File file2 = FileUtils.getFile(destination, this.getNewName(file));

    System.out.println("Copy " + file.getAbsolutePath() + " to " + file2.getAbsolutePath());

    try {
        FileUtils.moveFile(file, file2);
        this.observed = file2;
        return true;
    } catch (FileAlreadyExistsException e1){
        e1.printStackTrace();
        JOptionPane.showMessageDialog(null, file2.getAbsolutePath() + " already exists.", "Error", JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        new Catcher(e);
    }
    return false;
}
项目:tiny-remapper    文件:OutputConsumerPath.java   
@Override
public void accept(String clsName, byte[] data) {
    try {
        Path dstFile = dstDir.resolve(clsName + classSuffix);

        if (isJar && Files.exists(dstFile)) {
            if (Files.isDirectory(dstFile)) throw new FileAlreadyExistsException("dst file "+dstFile+" is a directory");

            Files.delete(dstFile); // workaround for sporadic FileAlreadyExistsException (Files.write should overwrite, jdk bug?)
        }

        createParentDirs(dstFile);
        Files.write(dstFile, data);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
项目:copybara    文件:FolderDestination.java   
@Override
public WriterResult write(TransformResult transformResult, Console console)
    throws ValidationException, RepoException, IOException {
  Path localFolder = getFolderPath(console);
  console.progress("FolderDestination: creating " + localFolder);
  try {
    Files.createDirectories(localFolder);
  } catch (FileAlreadyExistsException e) {
    // This exception message is particularly bad and we don't want to treat it as unhandled
    throw new RepoException("Cannot create '" + localFolder + "' because '" + e.getFile()
        + "' already exists and is not a directory");
  }
  console.progress("FolderDestination: deleting all files from " + localFolder);
  FileUtil.deleteFilesRecursively(localFolder, destinationFiles.relativeTo(localFolder));

  console.progress("FolderDestination: Copying contents of the workdir to " + localFolder);
  FileUtil.copyFilesRecursively(transformResult.getPath(), localFolder,
      CopySymlinkStrategy.FAIL_OUTSIDE_SYMLINKS);
  return WriterResult.OK;
}
项目:nnio    文件:FilesTest.java   
@Test
public void move() throws IOException {
  Path test1 = base.resolve("test1");
  Path test2 = base.resolve("test2");
  ByteArrayInputStream bais = new ByteArrayInputStream(data);
  Files.copy(bais, test1);
  assertArrayEquals(data, getFileContent(test1));
  Files.move(test1, test2);
  assertArrayEquals(data, getFileContent(test2));
  Path test3 = Files.createTempFile(base, "foo", ".txt");
  assertArrayEquals(new byte[0], getFileContent(test3));
  try {
    Files.move(test2, test3);
    fail();
  } catch (FileAlreadyExistsException ignored) {
    // Expected.
  }
  Files.delete(test3);
  Files.move(test2, test3);
  assertArrayEquals(data, getFileContent(test3));
}
项目:pravega    文件:FileSystemStorage.java   
private <T> T throwException(String segmentName, Exception e) throws StreamSegmentException {
    if (e instanceof NoSuchFileException || e instanceof FileNotFoundException) {
        throw new StreamSegmentNotExistsException(segmentName);
    }

    if (e instanceof FileAlreadyExistsException) {
        throw new StreamSegmentExistsException(segmentName);
    }

    if (e instanceof IndexOutOfBoundsException) {
        throw new IllegalArgumentException(e.getMessage());
    }

    if (e instanceof AccessControlException
            || e instanceof AccessDeniedException
            || e instanceof NonWritableChannelException) {
        throw new StreamSegmentSealedException(segmentName, e);
    }

    throw Lombok.sneakyThrow(e);
}
项目:communication    文件:Configuration.java   
/**
 * Store current properties to file.
 * Always overwrite.
 * @param filenameToSave file to save
 * @param comments comments on property file
 * @throws FileNotFoundException filenameToSave is empty
 * @throws FileAlreadyExistsException filenameToSave already exist
 */
public void store(String filenameToSave, String comments)
        throws FileNotFoundException, FileAlreadyExistsException {
    if (StringUtils.isEmpty(filenameToSave)) {
        throw new FileNotFoundException();
    }
    if (filenameToSave.equals(filename)) {
        throw new FileAlreadyExistsException(filenameToSave);
    }
    FileWriter fileWriter = null;
    BufferedWriter bufferedWriter = null;
    try {
        fileWriter = new FileWriter(filenameToSave, false);
        bufferedWriter = new BufferedWriter(fileWriter);
        prop.store(bufferedWriter, comments);
    } catch (IOException e) {
        logger.error("Fail on store properties.", e);
    } finally {
        IOUtils.closeQuite(fileWriter);
        IOUtils.closeQuite(bufferedWriter);
    }
}
项目:flink    文件:LocalFileSystem.java   
private boolean mkdirsInternal(File file) throws IOException {
    if (file.isDirectory()) {
            return true;
    }
    else if (file.exists() && !file.isDirectory()) {
        // Important: The 'exists()' check above must come before the 'isDirectory()' check to
        //            be safe when multiple parallel instances try to create the directory

        // exists and is not a directory -> is a regular file
        throw new FileAlreadyExistsException(file.getAbsolutePath());
    }
    else {
        File parent = file.getParentFile();
        return (parent == null || mkdirsInternal(parent)) && file.mkdir();
    }
}
项目:flink    文件:LocalFileSystem.java   
@Override
public FSDataOutputStream create(final Path filePath, final WriteMode overwrite) throws IOException {
    checkNotNull(filePath, "filePath");

    if (exists(filePath) && overwrite == WriteMode.NO_OVERWRITE) {
        throw new FileAlreadyExistsException("File already exists: " + filePath);
    }

    final Path parent = filePath.getParent();
    if (parent != null && !mkdirs(parent)) {
        throw new IOException("Mkdirs failed to create " + parent);
    }

    final File file = pathToFile(filePath);
    return new LocalDataOutputStream(file);
}
项目:bookery    文件:Converter.java   
private static void copyAllFiles() throws IOException {
    Path start = Paths.get("/Users/felixhusse1/Documents/fabian-books");
    Files.walkFileTree(start, new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            String filename = file.getFileName().toString();
            if (filename.contains(".epub")) {
                try {
                    Path destination = Paths.get("/Users/felixhusse1/Documents/only-epub", filename);
                    Files.copy(file, destination);
                    System.out.println("copied " + filename);
                } catch (FileAlreadyExistsException ex) {
                    //IGNORE..ouch
                }
            }

            return FileVisitResult.CONTINUE;
        }
    });
}
项目:SmartBackup    文件:SnapshotCreator.java   
/** {@inheritDoc} */
@Override
protected void createBackup() throws InterruptedException, IOException {
  SimpleDateFormat rfc8601Formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH_mm_ss'Z'");
  rfc8601Formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

  snapshotOutput = Paths.get(config.getBackupOutputDir(), rfc8601Formatter.format(new Date()));

  if (Files.exists(snapshotOutput)) {
    throw new FileAlreadyExistsException("Backup output directory already exists: " +
        snapshotOutput.toString());
  }

  Files.createDirectories(snapshotOutput);

  backupExcludes = new ArrayList<>(Arrays.asList(config.getBackupExcludes()));

  for (String file : config.getBackupIncludes()) {
    Files.walkFileTree(Paths.get(file), EnumSet.allOf(FileVisitOption.class),
        Integer.MAX_VALUE, new SnapshotVisitor());
  }
}
项目:Style    文件:Directory.java   
public Directory mkdir(String dir) throws FileAlreadyExistsException, FileOperationFailedException {
        dir = dir.trim();
        try {
                cd(dir);
        } catch (FileNotFoundException e) {
                File f;
                if (dir.startsWith("/")) {
                        f = new File(dir);
                } else {
                        f = new File(fullPath() + dir);
                }
                if (!f.mkdir()) throw new FileOperationFailedException("mkdir " + dir);
                try {
                        return new Directory(f);
                } catch (FileNotFoundException | NotDirectoryException e1) {
                        throw Style.$(e1);
                }
        } catch (NotDirectoryException ignore) {
        }
        throw new FileAlreadyExistsException(fullPath() + " " + dir);
}
项目:mobile-asset-generator    文件:ImageProcessor.java   
public static void exportImage(File inputFile, File outputDirectory, float preScale,
                               Density inputDensity, Density outputDensity, boolean overwrite) throws IOException {

    String outPath = outputDirectory.getAbsolutePath()
            + "/"   + outputDensity.getDrawableResourceDirectoryName()
            + "/" + inputFile.getName();

    File outFile = new File(outPath);
    if (!overwrite && outFile.exists()) {
        throw new FileAlreadyExistsException(outFile.getAbsolutePath());
    }

    outFile.getParentFile().mkdirs();
    BufferedImage inputImage = ImageIO.read(inputFile);
    String extension = getFileExtension(inputFile);
    float scale = preScale * outputDensity.getRatioToBaseDensity() / inputDensity.getRatioToBaseDensity();
    int scaledWidth = (int) (inputImage.getWidth() * scale);
    int scaledHeight = (int) (inputImage.getHeight() * scale);
    System.out.println(String.format(Locale.US, "%s: [%d, %d]: %s", extension, scaledWidth, scaledHeight, outPath));
    BufferedImage outputImage = getScaledInstance(inputImage, scaledWidth, scaledHeight, true);
    //write output image
    ImageIO.write(outputImage, extension, outFile);
}
项目:incubator-taverna-language    文件:RecursiveCopyFileVisitor.java   
public static void copyRecursively(final Path source,
        final Path destination, final CopyOption... copyOptions)
        throws IOException {
    final Set<CopyOption> copyOptionsSet = new HashSet<>(
            Arrays.asList(copyOptions));

    if (!isDirectory(source))
        throw new FileNotFoundException("Not a directory: " + source);
    if (isDirectory(destination)
            && !copyOptionsSet.contains(REPLACE_EXISTING))
        throw new FileAlreadyExistsException(destination.toString());
    Path destinationParent = destination.getParent();
    if (destinationParent != null && !isDirectory(destinationParent))
        throw new FileNotFoundException("Not a directory: "
                + destinationParent);

    RecursiveCopyFileVisitor visitor = new RecursiveCopyFileVisitor(
            destination, copyOptionsSet, source);
    Set<FileVisitOption> walkOptions = noneOf(FileVisitOption.class);
    if (!copyOptionsSet.contains(NOFOLLOW_LINKS))
        walkOptions = EnumSet.of(FOLLOW_LINKS);
    walkFileTree(source, walkOptions, MAX_VALUE, visitor);
}
项目:PerWorldInventory    文件:FlatFile.java   
@Override
public void saveToDatabase(Group group, GameMode gamemode, PWIPlayer player) {
    File file = getFile(gamemode, group, player.getUuid());
    ConsoleLogger.debug("Saving data for player '" + player.getName() + "' in file '" + file.getPath() + "'");

    try {
        createFileIfNotExists(file);
    } catch (IOException ex) {
        if (!(ex instanceof FileAlreadyExistsException)) {
            ConsoleLogger.severe("Error creating file '" + file.getPath() + "':", ex);
            return;
        }
    }

    ConsoleLogger.debug("Writing player data for player '" + player.getName() + "' to file");

    String data = playerSerializer.serialize(player);
    writeData(file, data);
}
项目:MineDoor    文件:ServerProperties.java   
public void save() throws IOException {
    File store = this.dispatcher.getPropertiesFile();
    if(store.isDirectory()){
        throw new FileAlreadyExistsException(store.getAbsolutePath(), "", "The config file already exists and is a directory");
    }else{
        if(!store.exists()){
            if(this.dispatcher.doNotCreateFile()){
                throw new IOException("No new file creation");
            }
            //noinspection ResultOfMethodCallIgnored
            store.createNewFile();
        }
        if(store.canWrite()){
            FileWriter writer = new FileWriter(store);
            this.store(writer, "MineDoor Configuration file");
            writer.close();
        }else{
            throw new IOException("Configuration: '" + store.getAbsolutePath() + "' is not writable.");
        }
    }
}
项目:goffish_v2    文件:N_Hop_Stats.java   
private boolean acquireLock(String lock) {
    boolean isAggregator;
    synchronized (N_Hop_Stats.class) {
        String fileName = "Lock_" + lock + ".lock";
        System.out.println("Lock " + fileName);


        Path filepath = logRootDir.resolve(fileName);
        try {
            Files.createFile(filepath);
            // if this succeeds, then this subgraph will perform agg for the partition
            isAggregator = true;
        } catch (FileAlreadyExistsException faeex) {
            isAggregator = false; // expected
        } catch (IOException e) {
            e.printStackTrace();
            isAggregator = false;
        }
    }
    System.out.println("Lock " + lock + " acqured by" + subgraph.getId());

    return isAggregator;

}