Java Code Examples for java.nio.file.Files.exists()

The following are Jave code examples for showing how to use exists() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ios-device-control   File: SimulatorDeviceHost.java   View Source Code Vote up 6 votes
/**
 * Depending on how the runtime is installed, the applications folder and system version
 * information can be located in one of two paths. The SDK path is used if it exists, otherwise
 * the simruntime directory is created on boot if it does not exist and is then used.
 */
private static Path runtimeRootPath(String productVersion) {
  Path runtimeRoot =
      Paths.get(
          "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform"
              + "/Developer/SDKs/iPhoneSimulator"
              + productVersion
              + ".sdk");
  if (!Files.exists(runtimeRoot)) {
    runtimeRoot =
        Paths.get(
            "/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS "
                + productVersion
                + ".simruntime/Contents/Resources/RuntimeRoot");
  }
  return runtimeRoot;
}
 
Example 2
Project: smarti   File: WikipediaDeIndexConfiguration.java   View Source Code Vote up 6 votes
@Bean(name=WIKIPEDIA_DE)
protected SolrCoreDescriptor getWikipediaDeCoreDescriptor() throws IOException {
    log.info("init CoreDescriptor with resource '{}'", wikipediaDeResource);
    SimpleCoreDescriptor cd = new SimpleCoreDescriptor(WIKIPEDIA_DE, Paths.get(wikipediaDeResource)){
        @Override
        public void initCoreDirectory(Path coreDir, Path sharedLibDir) throws IOException {
            if(!Files.exists(coreDir.resolve("core.properties"))){
                log.debug("copying wikipedia-de solr core to {}", coreDir);
                super.initCoreDirectory(coreDir, sharedLibDir);
            } else { //TODO: check version based on version number in core.properties
                log.info("using existing wikipedia-de solr core (if you want to update delete '{}' and restart)", coreDir);
            }
        }
    };
    return cd;
}
 
Example 3
Project: joal   File: TorrentFileProvider.java   View Source Code Vote up 6 votes
public TorrentFileProvider(final String confFolder, final ApplicationEventPublisher publisher) throws FileNotFoundException {
    if (StringUtils.isBlank(confFolder)) {
        throw new IllegalArgumentException("A config path is required.");
    }
    this.torrentFolder = Paths.get(confFolder).resolve("torrents");
    if (!Files.exists(torrentFolder)) {
        logger.error("Folder " + torrentFolder.toAbsolutePath() + " does not exists.");
        throw new FileNotFoundException(String.format("Torrent folder '%s' not found.", torrentFolder.toAbsolutePath()));
    }

    this.publisher = publisher;
    this.archiveFolder = torrentFolder.resolve("archived");
    this.torrentFiles = Collections.synchronizedMap(new HashMap<File, MockedTorrent>());
    this.watcher = new TorrentFileWatcher(this, torrentFolder);
    this.torrentFileChangeListener = new HashSet<>();
}
 
Example 4
Project: Amicus   File: YamlConfigFile.java   View Source Code Vote up 6 votes
public static YamlConfigFile load(@Nonnull final Path path,
                                  @Nullable final String resource,
                                  final boolean overwrite) throws IOException {
    if (overwrite) {
        Files.deleteIfExists(path);
    }

    if (!Files.exists(path)) {
        Files.createDirectories(path.getParent());
        Files.copy(YamlConfigFile.class.getResourceAsStream(resource), path);
    }

    final YAMLConfigurationLoader fileLoader = YAMLConfigurationLoader.builder().setPath(path).build();

    return new YamlConfigFile(path, fileLoader, fileLoader.load());
}
 
Example 5
Project: Elasticsearch   File: GatewayMetaState.java   View Source Code Vote up 6 votes
/**
 * Throws an IAE if a pre 0.19 state is detected
 */
private void ensureNoPre019State() throws Exception {
    for (Path dataLocation : nodeEnv.nodeDataPaths()) {
        final Path stateLocation = dataLocation.resolve(MetaDataStateFormat.STATE_DIR_NAME);
        if (!Files.exists(stateLocation)) {
            continue;
        }
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(stateLocation)) {
            for (Path stateFile : stream) {
                if (logger.isTraceEnabled()) {
                    logger.trace("[upgrade]: processing [" + stateFile.getFileName() + "]");
                }
                final String name = stateFile.getFileName().toString();
                if (name.startsWith("metadata-")) {
                    throw new IllegalStateException("Detected pre 0.19 metadata file please upgrade to a version before "
                            + Version.CURRENT.minimumCompatibilityVersion()
                            + " first to upgrade state structures - metadata found: [" + stateFile.getParent().toAbsolutePath());
                }
            }
        }
    }
}
 
Example 6
Project: elasticsearch_my   File: KeyStoreWrapper.java   View Source Code Vote up 6 votes
/**
 * Loads information about the Elasticsearch keystore from the provided config directory.
 *
 * {@link #decrypt(char[])} must be called before reading or writing any entries.
 * Returns {@code null} if no keystore exists.
 */
public static KeyStoreWrapper load(Path configDir) throws IOException {
    Path keystoreFile = keystorePath(configDir);
    if (Files.exists(keystoreFile) == false) {
        return null;
    }

    SimpleFSDirectory directory = new SimpleFSDirectory(configDir);
    try (IndexInput indexInput = directory.openInput(KEYSTORE_FILENAME, IOContext.READONCE)) {
        ChecksumIndexInput input = new BufferedChecksumIndexInput(indexInput);
        CodecUtil.checkHeader(input, KEYSTORE_FILENAME, FORMAT_VERSION, FORMAT_VERSION);
        byte hasPasswordByte = input.readByte();
        boolean hasPassword = hasPasswordByte == 1;
        if (hasPassword == false && hasPasswordByte != 0) {
            throw new IllegalStateException("hasPassword boolean is corrupt: "
                + String.format(Locale.ROOT, "%02x", hasPasswordByte));
        }
        String type = input.readString();
        String secretKeyAlgo = input.readString();
        byte[] keystoreBytes = new byte[input.readInt()];
        input.readBytes(keystoreBytes, 0, keystoreBytes.length);
        CodecUtil.checkFooter(input);
        return new KeyStoreWrapper(hasPassword, type, secretKeyAlgo, keystoreBytes);
    }
}
 
Example 7
Project: chipKIT-importer   File: ArduinoBuilderRunner.java   View Source Code Vote up 6 votes
private String[] createDependencyResolutionCommand( Path gccPath, Path corePath, Path variantPath, List<Path> libraryPaths, Path file ) {
    List <String> commandElements = new ArrayList<>();
    commandElements.add( gccPath.toString() );
    commandElements.add( "-I" );
    commandElements.add( corePath.toString() );
    commandElements.add( "-I" );
    commandElements.add( variantPath.toString() );
    for ( Path libPath : libraryPaths ) {
        commandElements.add( "-I" );
        commandElements.add( libPath.toAbsolutePath().toString() );
        Path utilityPath = libPath.resolve("utility");
        if ( Files.exists(utilityPath) ) {
            commandElements.add( "-I" );
            commandElements.add( utilityPath.toAbsolutePath().toString() );
        }
    }        
    commandElements.add( "-MM" );
    commandElements.add( file.toAbsolutePath().toString() );
    return commandElements.toArray( new String[commandElements.size()] );
}
 
Example 8
Project: EagleFactions   File: MainConfig.java   View Source Code Vote up 6 votes
@Override
public void setup()
{
    if (! Files.exists(configFile))
    {
        try
        {
            Files.createFile(configFile);
            load();
            populate();
            save();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    else
    {
        load();
    }
}
 
Example 9
Project: openjdk-jdk10   File: ShellFolder.java   View Source Code Vote up 5 votes
/**
 * Return a shell folder from a file object
 * @exception FileNotFoundException if file does not exist
 */
public static ShellFolder getShellFolder(File file) throws FileNotFoundException {
    if (file instanceof ShellFolder) {
        return (ShellFolder)file;
    }

    if (!Files.exists(Paths.get(file.getPath()), LinkOption.NOFOLLOW_LINKS)) {
        throw new FileNotFoundException();
    }
    return shellFolderManager.createShellFolder(file);
}
 
Example 10
Project: pgcodekeeper   File: ProjectUpdater.java   View Source Code Vote up 5 votes
private void safeCleanProjectDir(Path dirTmp) throws IOException {
    for (WORK_DIR_NAMES subdirName : WORK_DIR_NAMES.values()) {
        String sSubdirName = subdirName.toString();
        Path dirOld = dirExport.resolve(sSubdirName);
        if (Files.exists(dirOld)) {
            Files.move(dirOld, dirTmp.resolve(sSubdirName), StandardCopyOption.ATOMIC_MOVE);
        }
    }
}
 
Example 11
Project: mxisd   File: KeyManager.java   View Source Code Vote up 5 votes
@PostConstruct
public void build() {
    try {
        keySpecs = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.CURVE_ED25519_SHA512);
        signEngine = new EdDSAEngine(MessageDigest.getInstance(keySpecs.getHashAlgorithm()));
        keys = new ArrayList<>();

        Path privKey = Paths.get(keyCfg.getPath());

        if (!Files.exists(privKey)) {
            KeyPair pair = (new KeyPairGenerator()).generateKeyPair();
            String keyEncoded = Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded());
            FileUtils.writeStringToFile(privKey.toFile(), keyEncoded, StandardCharsets.ISO_8859_1);
            keys.add(pair);
        } else {
            if (Files.isDirectory(privKey)) {
                throw new RuntimeException("Invalid path for private key: " + privKey.toString());
            }

            if (Files.isReadable(privKey)) {
                byte[] seed = Base64.getDecoder().decode(FileUtils.readFileToString(privKey.toFile(), StandardCharsets.ISO_8859_1));
                EdDSAPrivateKeySpec privKeySpec = new EdDSAPrivateKeySpec(seed, keySpecs);
                EdDSAPublicKeySpec pubKeySpec = new EdDSAPublicKeySpec(privKeySpec.getA(), keySpecs);
                keys.add(new KeyPair(new EdDSAPublicKey(pubKeySpec), new EdDSAPrivateKey(privKeySpec)));
            }
        }
    } catch (NoSuchAlgorithmException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Project: nitrite-database   File: NitriteManager.java   View Source Code Vote up 5 votes
private void createSampleDb() {
    String dbFilePath = Paths.get("").toAbsolutePath().toString() + "/sample.db";
    if (!Files.exists(Paths.get(dbFilePath))) {
        Nitrite db = Nitrite.builder()
                .filePath(dbFilePath)
                .openOrCreate();

        ObjectRepository<Company> companyRepository = db.getRepository(Company.class);
        ObjectRepository<Employee> employeeRepository = db.getRepository(Employee.class);

        Employee[] dummy = new Employee[0];
        for (int i = 0; i < 10; i++) {
            Company company = DataGenerator.generateCompanyRecord();
            companyRepository.insert(company);

            for (List<Employee> employeeList : company.getEmployeeRecord().values()) {
                if (employeeList != null && !employeeList.isEmpty()) {
                    employeeRepository.insert(employeeList.toArray(dummy));
                }
            }
        }

        db.commit();
        db.close();
    } else {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Sample Database");
        alert.setHeaderText("Sample Database Already Exists");
        alert.getDialogPane().setContent(new Label(dbFilePath));

        alert.showAndWait();
    }
    dbFile.setText(dbFilePath);
}
 
Example 13
Project: openjdk-jdk10   File: JmodTask.java   View Source Code Vote up 5 votes
@Override
public Path convert(String value) {
    try {
        Path path = CWD.resolve(value);
        if (Files.exists(path)) {
            if (!Files.isDirectory(path))
                throw new CommandException("err.cannot.create.dir", path);
        }
        return path;
    } catch (InvalidPathException x) {
        throw new CommandException("err.path.not.valid", value);
    }
}
 
Example 14
Project: incubator-netbeans   File: ModuleTest.java   View Source Code Vote up 5 votes
private static Path getModulesRoot() {
    try {
        final File javaHome = new File(JDK9_HOME == null ? System.getProperty("java.home") : JDK9_HOME);    //NOI18N
        final File jrtProvider = new File(new File(javaHome, "lib"), "jrt-fs.jar");  //NOI18N
        if (!jrtProvider.exists()) {
            return null;
        }
        final ClassLoader cl = new URLClassLoader(
                new URL[]{jrtProvider.toURI().toURL()},
                ModuleTest.class.getClassLoader());
        FileSystemProvider provider = null;
        for (FileSystemProvider p : ServiceLoader.load(FileSystemProvider.class, cl)) {
            if ("jrt".equals(p.getScheme())) {  //NOI18N
                provider = p;
                break;
            }
        }
        if (provider == null) {
            return null;
        }
        final Path jimageRoot = provider.getPath(URI.create("jrt:///"));    //NOI18N
        final Path modules = jimageRoot.resolve("modules");
        return Files.exists(modules) ? modules : jimageRoot;
    } catch (IOException ioe) {
        LOG.log(Level.WARNING, "Cannot load jrt nio provider.", ioe);   //NOI18N
        return null;
    }
}
 
Example 15
Project: httrack2warc   File: HttrackCrawl.java   View Source Code Vote up 5 votes
public void forEach(RecordConsumer action) throws IOException {
    if (Files.exists(dir.resolve("hts-cache/new.txt"))) {
        forEachByTxt(action);
    } else if (Files.exists(dir.resolve("logs/debug"))) {
        forEachByDebugLogs(action);
    } else {
        throw new IOException("Both hts-cache/new.txt and logs/debug are missing. I can't handle this crawl.");
    }
}
 
Example 16
Project: CloudNet   File: ConfigAbstract.java   View Source Code Vote up 5 votes
public ConfigAbstract(Document defaults, Path path)
{
    if(!Files.exists(path))
    {
        defaults.saveAsConfig(path);
    }
    this.path = path;
}
 
Example 17
Project: StreamDeckCore   File: IconHelper.java   View Source Code Vote up 4 votes
public static IconPackage loadIconPackage(String pathToZip) throws IOException, URISyntaxException {
	if (packageCache.containsKey(pathToZip))
		return packageCache.get(pathToZip);
	Path path = Paths.get(pathToZip);
	URI uri = new URI("jar", path.toUri().toString(), null);

	Map<String, String> env = new HashMap<>();
	env.put("create", "true");

	try (FileSystem fileSystem = FileSystems.newFileSystem(uri, env)) {
		Path iconPath = fileSystem.getPath("icon.png");
		// load main icon
		byte[] icon = IconHelper.loadImage(iconPath);
		// load animation, if exists
		Path animFile = fileSystem.getPath("animation.json");
		AnimationStack animation = null;
		if (Files.exists(animFile)) {
			String text = new String(Files.readAllBytes(animFile), StandardCharsets.UTF_8);
			Gson g = new Gson();
			animation = g.fromJson(text, AnimationStack.class);
			// Load animation frames
			int frameIndex = 0;
			Path frameFile = fileSystem.getPath((frameIndex++) + ".png");
			List<byte[]> frameList = new LinkedList<>();
			while (Files.exists(frameFile)) {
				byte[] frame = IconHelper.loadImage(frameFile);
				frameList.add(frame);
				frameFile = fileSystem.getPath((frameIndex++) + ".png");
			}
			byte[][] frames = new byte[frameList.size()][];
			for (int i = 0; i < frames.length; i++) {
				frames[i] = frameList.get(i);
			}
			animation.setFrames(frames);
		}
		fileSystem.close();
		IconPackage iconPackage = new IconPackage(icon, animation);
		packageCache.put(pathToZip, iconPackage);
		return iconPackage;
	}
}
 
Example 18
Project: openjdk-jdk10   File: Helper.java   View Source Code Vote up 4 votes
private Helper(Path jdkHome) throws IOException {
    this.stdjmods = jdkHome.resolve("jmods").normalize();
    if (!Files.exists(stdjmods)) {
        throw new IOException("Standard jMods do not exist.");
    }
    this.fs = FileSystems.getFileSystem(URI.create("jrt:/"));

    Path javabase = fs.getPath("/modules/java.base");
    this.bootClasses = Files.find(javabase, Integer.MAX_VALUE,
            (file, attrs) -> file.toString().endsWith(".class"))
            .map(Object::toString)
            .map(s -> s.substring("/modules".length()))
            .collect(Collectors.toList());

    if (bootClasses.isEmpty()) {
        throw new AssertionError("No boot class to check against");
    }

    this.jmods = Paths.get("jmods").toAbsolutePath();
    Files.createDirectories(jmods);
    this.jars = Paths.get("jars").toAbsolutePath();
    Files.createDirectories(jars);
    this.explodedmods = Paths.get("explodedmods").toAbsolutePath();
    Files.createDirectories(explodedmods);
    this.explodedmodssrc = explodedmods.resolve("src");
    Files.createDirectories(explodedmodssrc);
    this.jarssrc = jars.resolve("src");
    Files.createDirectories(jarssrc);
    this.jmodssrc = jmods.resolve("src");
    Files.createDirectories(jmodssrc);
    this.explodedmodsclasses = explodedmods.resolve("classes");
    Files.createDirectories(explodedmodsclasses);
    this.jmodsclasses = jmods.resolve("classes");
    Files.createDirectories(jmodsclasses);
    this.jarsclasses = jars.resolve("classes");
    Files.createDirectories(jarsclasses);
    this.images = Paths.get("images").toAbsolutePath();
    Files.createDirectories(images);
    this.extracted = Paths.get("extracted").toAbsolutePath();
    Files.createDirectories(extracted);
    this.recreated = Paths.get("recreated").toAbsolutePath();
    Files.createDirectories(recreated);
}
 
Example 19
Project: neoscada   File: AbstractMergeWatcher.java   View Source Code Vote up 4 votes
public AbstractMergeWatcher ( Path path, final long delay, final TimeUnit timeUnit ) throws IOException
{
    this.path = path;
    this.delay = delay;
    this.timeUnit = timeUnit;

    if ( !Files.exists ( path ) )
    {
        throw new IllegalArgumentException ( String.format ( "Failed to watch: %s. Path does not exists.", path ) );
    }

    this.ws = path.getFileSystem ().newWatchService ();

    if ( Files.isRegularFile ( path ) )
    {
        path = path.getParent ();
        logger.debug ( "Watching parent directory: {}", path );
        path.register ( this.ws, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE );
        this.watchFile = true;
    }
    else
    {
        logger.debug ( "Watching directory: {}", path );
        path.register ( this.ws, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE );
        this.watchFile = false;
    }

    this.watchPath = path;

    this.runner = new Thread () {
        @Override
        public void run ()
        {
            try
            {
                logger.info ( "Starting scanner thread" );
                scanner ();
            }
            finally
            {
                logger.info ( "Exiting scanner thread" );
            }
        }
    };
    this.runner.start ();

    this.executor = ScheduledExportedExecutorService.newSingleThreadExportedScheduledExecutor ( "org.eclipse.scada.ca.updater/MergeWatcher" );
}
 
Example 20
Project: omero-ms-queue   File: FileOps.java   View Source Code Vote up 3 votes
/**
 * Copies the source file to the destination path, overriding it if it 
 * exists already. If the source file does not exist, this method does
 * nothing.
 * @param source path to the file to copy.
 * @param destination path to the copied file.
 * @throws NullPointerException if any argument is {@code null}.
 * <p>The following checked exceptions are rethrown as unchecked (i.e.
 * the exception is masked as a runtime exception and thrown as is without
 * wrapping it in a {@code RuntimeException}):
 * <br>{@link IOException} if an I/O error occurs.
 * </p>
 */
public static void copy(Path source, Path destination) {
    requireNonNull(source, "source");
    requireNonNull(destination, "destination");
    
    if (Files.exists(source)) {
        runUnchecked(() -> Files.copy(source, destination, 
                                      StandardCopyOption.REPLACE_EXISTING));
    }
}