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

The following are Jave code examples for showing how to use notExists() 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: BeamTeamDiscordBot   File: ConstellationManager.java   View Source Code Vote up 6 votes
private static void handleAnnouncements(LiveEvent event, JsonObject payload) {
	try {
		if (Files.notExists(Paths.get("payloads\\"))) {
			new File("payloads\\").mkdir();
		}

		Logger logger = Logger.getLogger("payload-announcement");
		FileHandler fh = new FileHandler("payloads\\" + logger.getName() + ".json");
		SimpleFormatter formatter = new SimpleFormatter();
		fh.setFormatter(formatter);

		logger.addHandler(fh);

		logger.log(Level.INFO, payload.toString());
	} catch (SecurityException | IOException e) {}
}
 
Example 2
Project: openjdk-jdk10   File: ExcludeJmodSectionPluginTest.java   View Source Code Vote up 6 votes
private Path createImage(String outputDir, List<String> options,
                         List<String> expectedFiles) {
    System.out.println("jlink " + options.toString());
    int rc = JLINK_TOOL.run(System.out, System.out,
                            options.toArray(new String[0]));
    assertTrue(rc == 0);

    Path d = IMAGES_DIR.resolve(outputDir);
    for (String fn : expectedFiles) {
        Path path = d.resolve(fn);
        if (Files.notExists(path)) {
            throw new RuntimeException(path + " not found");
        }
    }
    return d;
}
 
Example 3
Project: RPGInventory   File: Config.java   View Source Code Vote up 6 votes
public static void loadConfig(RPGInventory plugin) {
    configFile = plugin.getDataPath().resolve("config.yml");
    if (Files.notExists(configFile)) {
        plugin.saveDefaultConfig();

        try {
            Path destination = plugin.getDataPath().resolve("config-example.yml");
            Files.copy(configFile, destination, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    plugin.reloadConfig();
    Config.config = plugin.getConfig();
}
 
Example 4
Project: openjdk-jdk10   File: Basic.java   View Source Code Vote up 6 votes
@BeforeClass
public void setup() {
    theFileSystem = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path modulesPath = Paths.get(System.getProperty("java.home"),
            "lib", "modules");
    isExplodedBuild = Files.notExists(modulesPath);
    if (isExplodedBuild) {
        System.out.printf("%s doesn't exist.", modulesPath.toString());
        System.out.println();
        System.out.println("It is most probably an exploded build."
                + " Skip non-default FileSystem testing.");
        return;
    }

    Map<String, String> env = new HashMap<>();
    // set java.home property to be underlying java.home
    // so that jrt-fs.jar loading is exercised.
    env.put("java.home", System.getProperty("java.home"));
    try {
        fs = FileSystems.newFileSystem(URI.create("jrt:/"), env);
    } catch (IOException ioExp) {
        throw new RuntimeException(ioExp);
    }
}
 
Example 5
Project: pgcodekeeper   File: PgImport.java   View Source Code Vote up 5 votes
@Override
public boolean isPageComplete(){
    //empty path: show default message
    if (txtPath.getText().isEmpty()) {
        setErrorMessage(null);
        return false;
    }

    String err = null;
    String name = txtName.getText();
    if (name.isEmpty()) {
        err = Messages.PgImport_error_no_name;
    }
    Path path = Paths.get(txtPath.getText());
    if (Files.exists(path.resolve(FILE_PROJECT))) {
        //if has .project
        err = Messages.PgImportWizardImportPage_already_exist;
    } else if (Files.exists(path.resolve(FILE_METADATA))) {
        //if has .metadata
        err = Messages.PgImport_error_metadata;
    } else if (Files.notExists(path.resolve(ApgdiffConsts.FILENAME_WORKING_DIR_MARKER))) {
        //if don't have .pgCodekeeper
        err = Messages.PgImportWizardImportPage_no_project;
    } else if (isInWorkspaceRoot(path) && !path.getFileName().toString().equals(name)) {
        //if project in root of workspace, it must have default name
        err = Messages.PgImport_error_default_name;
    }
    setErrorMessage(err);
    return err == null;
}
 
Example 6
Project: digital-display-garden-iteration-4-dorfner-v2   File: TestPhotos.java   View Source Code Vote up 5 votes
@Before
public void flagDeletePos() {
    if (Files.notExists(Paths.get(".photos/"))) {
        photosExist = false;
    } else {
        photosExist = true;
    }
}
 
Example 7
Project: openjdk-jdk10   File: BasicTest.java   View Source Code Vote up 5 votes
public void run() throws Throwable {
    if (Files.notExists(jdkMods)) {
        return;
    }

    if (!CompilerUtils.compile(src, classes)) {
        throw new AssertionError("Compilation failure. See log.");
    }

    Files.createDirectories(jmods);
    Files.createDirectories(jars);
    Path jarfile = jars.resolve("test.jar");
    JarUtils.createJarFile(jarfile, classes);

    Path image = Paths.get("mysmallimage");
    runJmod(jarfile.toString(), TEST_MODULE, true);
    runJlink(image, TEST_MODULE, "--compress", "2", "--launcher", "foo=" + TEST_MODULE);
    execute(image, "foo");

    Files.delete(jmods.resolve(TEST_MODULE + ".jmod"));

    image = Paths.get("myimage");
    runJmod(classes.toString(), TEST_MODULE, true);
    runJlink(image, TEST_MODULE, "--launcher", "bar=" + TEST_MODULE);
    execute(image, "bar");

    Files.delete(jmods.resolve(TEST_MODULE + ".jmod"));

    image = Paths.get("myimage2");
    runJmod(classes.toString(), TEST_MODULE, false /* no ModuleMainClass! */);
    // specify main class in --launcher command line
    runJlink(image, TEST_MODULE, "--launcher", "bar2=" + TEST_MODULE + "/jdk.test.Test");
    execute(image, "bar2");

}
 
Example 8
Project: RPGInventory   File: BackpackManager.java   View Source Code Vote up 5 votes
public static boolean init(RPGInventory instance) {
    if (!isEnabled()) {
        return false;
    }

    try {
        Path petsFile = RPGInventory.getInstance().getDataPath().resolve("backpacks.yml");
        if (Files.notExists(petsFile)) {
            RPGInventory.getInstance().saveResource("backpacks.yml", false);
        }

        FileConfiguration petsConfig = YamlConfiguration.loadConfiguration(petsFile.toFile());

        BACKPACK_TYPES.clear();
        for (String key : petsConfig.getConfigurationSection("backpacks").getKeys(false)) {
            tryToAddBackpack(key, petsConfig.getConfigurationSection("backpacks." + key));
        }

        BackpackManager.loadBackpacks();
        RPGInventory.getPluginLogger().info(BACKPACK_TYPES.size() + " backpack type(s) has been loaded");
        RPGInventory.getPluginLogger().info(BACKPACKS.size() + " backpack(s) has been loaded");
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    if (BACKPACK_TYPES.size() == 0) {
        return false;
    }

    BACKPACK_LIMIT = Config.getConfig().getInt("backpacks.limit", 0);

    // Register events
    instance.getServer().getPluginManager().registerEvents(new BackpackListener(), instance);
    return true;
}
 
Example 9
Project: openjdk-jdk10   File: VerifyJimage.java   View Source Code Vote up 5 votes
public static void main(String... args) throws Exception {

        String home = System.getProperty("java.home");
        Path bootimagePath = Paths.get(home, "lib", "modules");
        if (Files.notExists(bootimagePath)) {
             System.out.println("Test skipped, not an images build");
             return;
        }

        long start = System.nanoTime();
        int numThreads = Integer.getInteger("jdk.test.threads", 1);
        JImageReader reader = newJImageReader();
        VerifyJimage verify = new VerifyJimage(reader, numThreads);
        if (args.length == 0) {
            // load classes from jimage
            verify.loadClasses();
        } else {
            Path dir = Paths.get(args[0]);
            if (Files.notExists(dir) || !Files.isDirectory(dir)) {
                throw new RuntimeException("Invalid argument: " + dir);
            }
            verify.compareExplodedModules(dir);
        }
        verify.waitForCompletion();
        long end = System.nanoTime();
        int entries = reader.entries();
        System.out.format("%d entries %d files verified: %d ms %d errors%n",
                          entries, verify.count.get(),
                          TimeUnit.NANOSECONDS.toMillis(end - start), failed.size());
        for (String f : failed) {
            System.err.println(f);
        }
        if (!failed.isEmpty()) {
            throw new AssertionError("Test failed");
        }
    }
 
Example 10
Project: student_database   File: DatabaseHelper.java   View Source Code Vote up 5 votes
public boolean checkDBFile() {
    Path path = Paths.get(DB_NAME);

    if (Files.exists(path)) {
        System.out.println("Exists");
        return true;
    } else if (Files.notExists(path)) {
        return false;
    } else {
        return false;
    }
}
 
Example 11
Project: visitormanagement   File: Util.java   View Source Code Vote up 5 votes
/**
 * @param baseDirName
 * @param imageDirName
 * @return
 * @throws IOException
 */
public static Path createFileDirectory(String baseDirName, String...imageDirName) throws IOException{
	Path path = Paths.get(baseDirName, imageDirName);
	if (Files.notExists(path)) {
		Files.createDirectories(path);
	}	
	return path;
}
 
Example 12
Project: openjdk-jdk10   File: ImageModules.java   View Source Code Vote up 5 votes
static String getJava(Path image) {
    boolean isWindows = System.getProperty("os.name").startsWith("Windows");
    Path java = image.resolve("bin").resolve(isWindows ? "java.exe" : "java");
    if (Files.notExists(java))
        throw new RuntimeException(java + " not found");
    return java.toAbsolutePath().toString();
}
 
Example 13
Project: message-broker   File: SslHandlerFactory.java   View Source Code Vote up 5 votes
private Path getPath(String storePath) {
    Path path = Paths.get(storePath);

    if (Files.notExists(path)) {
        String brokerHome = System.getProperty(CommonConstants.MESSAGE_BROKER_HOME_PROPERTY);
        path = Paths.get(brokerHome + File.separator + storePath);
    }
    return path;
}
 
Example 14
Project: thirdcoast   File: TalonProvisioner.java   View Source Code Vote up 5 votes
static void checkFileExists(File file) {
  Path path = file.toPath();
  if (Files.notExists(path)) {
    logger.info("{} missing, copying default", file);
    InputStream is = TalonProvisioner.class.getResourceAsStream(DEFAULT_CONFIG);
    try {
      Files.copy(is, path);
    } catch (IOException e) {
      logger.error("unable to copy default config to " + path, e);
    }
  }
}
 
Example 15
Project: openjdk-jdk10   File: AllModulePath.java   View Source Code Vote up 5 votes
@Test
public void testAddModules() throws Throwable {
    if (Files.notExists(JMODS)) {
        return;
    }

    // create custom image
    Path image = Paths.get("image2");
    createImage(image,
                "--add-modules", "m1,test",
                "--add-modules", "ALL-MODULE-PATH",
                "--limit-modules", "java.base");

    checkModules(image, Set.of("m1", "test", "java.base"));
}
 
Example 16
Project: RPGInventory   File: InventoryManager.java   View Source Code Vote up 4 votes
private static boolean isNewPlayer(Player player) {
    Path dataFolder = RPGInventory.getInstance().getDataFolder().toPath();
    return Files.notExists(dataFolder.resolve("inventories/" + player.getUniqueId() + ".inv"));
}
 
Example 17
Project: openjdk-jdk10   File: ImageModules.java   View Source Code Vote up 4 votes
@Test(dataProvider = "twoModules")
public void doNotResolveByDefaultTwoModules(String extraFirstJmodArg,
                                            String extraSecondJmodArg,
                                            List<String> addModsTokens,
                                            Consumer<ToolResult> assertExitCode,
                                            List<String> expectedOutput,
                                            List<String> unexpectedOutput)
    throws Throwable
{
    if (Files.notExists(JDK_JMODS)) {
        System.out.println("JDK jmods not found test cannot run.");
        return;
    }

    FileUtils.deleteFileTreeUnchecked(JMODS_DIR);
    FileUtils.deleteFileTreeUnchecked(IMAGE);
    Files.createDirectories(JMODS_DIR);
    Path writerJmod = JMODS_DIR.resolve("writer.jmod");
    Path converterJmod = JMODS_DIR.resolve("converter.jmod");

    jmod("create",
         extraFirstJmodArg,
         "--class-path", MODS_DIR.resolve("message.writer").toString(),
         writerJmod.toString());

    jmod("create",
         "--class-path", MODS_DIR.resolve("message.converter").toString(),
         extraSecondJmodArg,
         converterJmod.toString())
        .assertSuccess();

    String mpath = JDK_JMODS.toString() + File.pathSeparator + JMODS_DIR.toString();
    jlink("--module-path", mpath,
          "--add-modules", JAVA_BASE + ",message.writer,message.converter",
          "--output", IMAGE.toString())
         .assertSuccess();

    for (String addModsToken : addModsTokens) {
        String[] props = new String[] {"", "-Djdk.system.module.finder.disabledFastPath"};
        for (String systemProp : props)
            java(IMAGE,
                 systemProp,
                 "--add-modules", addModsToken,
                 "-cp", CP_DIR.toString(),
                 "test.WriteUpperCase", "hello chegar !!!")
                .resultChecker(assertExitCode)
                .resultChecker(r -> {
                    expectedOutput.forEach(e -> r.assertContains(e));
                    unexpectedOutput.forEach(e -> r.assertDoesNotContains(e));
                });
    }
}
 
Example 18
Project: cf-mta-deploy-service   File: FileUtils.java   View Source Code Vote up 4 votes
public static void copyFile(Path fromPath, Path toPath) throws IOException {
    if (Files.notExists(toPath.getParent())) {
        Files.createDirectories(toPath.getParent());
    }
    Files.copy(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
}
 
Example 19
Project: CSS-Editor-FX   File: Context.java   View Source Code Vote up 4 votes
private static void loadSkin() {
  // load default skins
  for (SkinStyle ss : DefaultSkin.values()) {
    SKIN.addSkin(ss);
  }
  // load skin files in /skin
  Path skinFolder = HOME_PATH.resolve("skin");
  try {
    if (Files.notExists(skinFolder)) {
      Files.createDirectory(skinFolder);
    } else {
      Files.newDirectoryStream(skinFolder).forEach(path -> {
        String fileName = path.getFileName().toString();
        if (!Files.isDirectory(path) && (fileName.endsWith(".css") ||
            fileName.endsWith(".bss"))) {
          String url = path.toUri().toString();
          String name = StringUtil.upperFirst(fileName.substring(0, fileName.length() - 4));
          SKIN.addSkin(new SkinStyle() {
            @Override
            public String getURL() {
              return url;
            }

            @Override
            public String getName() {
              return name;
            }
          });
        }
      });
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
  SKIN.getSkinList().stream().map(SkinStyle::getURL).map(s -> "loaded skin: " +
      s).forEach(log::debug);

  SKIN.changeSkin(DefaultSkin.CLASSIC);
  String configSkin = Config.getProperty(ConfigKey.SKIN, null);
  if (configSkin != null) {
    SKIN.getSkinList().stream()
        .filter(s -> s.getName().equals(configSkin))
        .findAny()
        .ifPresent(s -> SKIN.changeSkin(s));
  }
  JavaFxObservable.fromObservableValue(SKIN.skinProperty())
      .subscribe(skin -> Config.setProperty(ConfigKey.SKIN, skin.getName()));
}
 
Example 20
Project: cloudterm   File: IOHelper.java   View Source Code Vote up 4 votes
public static synchronized void copyLibPty(Path dataDir) throws IOException {

        Path donePath = dataDir.resolve(".DONE");

        if (Files.exists(donePath)) {
            return;
        }

        Set<String> nativeFiles = getNativeFiles();

        for (String nativeFile : nativeFiles) {
            Path nativePath = dataDir.resolve(nativeFile);

            if (Files.notExists(nativePath)) {
                Files.createDirectories(nativePath.getParent());
                InputStream inputStream = IOHelper.class.getResourceAsStream("/" + nativeFile);
                Files.copy(inputStream, nativePath);
                close(inputStream);
            }

        }

        Files.createFile(donePath);

    }