List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:Test.java
public static void main(String[] args) throws Exception { Path listing = Paths.get("/usr/bin/zip"); System.out.println("Parent Path [" + listing.getParent() + "]"); }
From source file:Main.java
public static void main(String[] args) { Path path = Paths.get("C:", "tutorial/Java/JavaFX", "Topic.txt"); System.out.println(path.getParent()); }
From source file:edu.jhu.hlt.concrete.ingesters.gigaword.GigawordGzProcessor.java
public static void main(String... args) { Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler()); if (args.length != 2) { LOGGER.info("This program takes 2 arguments."); LOGGER.info("First: the path to a .gz file that is part of the English Gigaword v5 corpus."); LOGGER.info("Second: the path to the output file (a .tar.gz with communication files)."); LOGGER.info("Example usage:"); LOGGER.info("{} {} {}", GigawordGzProcessor.class.getName(), "/path/to/LDC/sgml/.gz", "/path/to/out.tar.gz"); System.exit(1);//from www.j av a2s . c o m } String inPathStr = args[0]; String outPathStr = args[1]; Path inPath = Paths.get(inPathStr); if (!Files.exists(inPath)) LOGGER.error("Input path {} does not exist. Try again with the right path.", inPath.toString()); Path outPath = Paths.get(outPathStr); Optional<Path> parent = Optional.ofNullable(outPath.getParent()); // lambda does not allow caught exceptions. if (parent.isPresent()) { if (!Files.exists(outPath.getParent())) { LOGGER.info("Attempting to create output directory: {}", outPath.toString()); try { Files.createDirectories(outPath); } catch (IOException e) { LOGGER.error("Caught exception creating output directory.", e); } } } GigawordDocumentConverter conv = new GigawordDocumentConverter(); Iterator<Communication> iter = conv.gzToStringIterator(inPath); try (OutputStream os = Files.newOutputStream(outPath); BufferedOutputStream bos = new BufferedOutputStream(os, 1024 * 8 * 16); GzipCompressorOutputStream gout = new GzipCompressorOutputStream(bos); TarArchiver archiver = new TarArchiver(gout);) { while (iter.hasNext()) { Communication c = iter.next(); LOGGER.info("Adding Communication {} [UUID: {}] to archive.", c.getId(), c.getUuid().getUuidString()); archiver.addEntry(new ArchivableCommunication(c)); } } catch (IOException e) { LOGGER.error("Caught IOException during output.", e); } }
From source file:com.github.houbin217jz.thumbnail.Thumbnail.java
public static void main(String[] args) { Options options = new Options(); options.addOption("s", "src", true, "????????????"); options.addOption("d", "dst", true, ""); options.addOption("r", "ratio", true, "/??, 30%???0.3????????"); options.addOption("w", "width", true, "(px)"); options.addOption("h", "height", true, "?(px)"); options.addOption("R", "recursive", false, "???????"); HelpFormatter formatter = new HelpFormatter(); String formatstr = "java -jar thumbnail.jar " + "[-s/--src <path>] " + "[-d/--dst <path>] " + "[-r/--ratio double] " + "[-w/--width integer] " + "[-h/--height integer] " + "[-R/--recursive] "; CommandLineParser parser = new PosixParser(); CommandLine cmd = null;//w w w .ja v a 2 s.co m try { cmd = parser.parse(options, args); } catch (ParseException e1) { formatter.printHelp(formatstr, options); return; } final Path srcDir, dstDir; final Integer width, height; final Double ratio; // if (cmd.hasOption("s")) { srcDir = Paths.get(cmd.getOptionValue("s")).toAbsolutePath(); } else { srcDir = Paths.get("").toAbsolutePath(); //?? } // if (cmd.hasOption("d")) { dstDir = Paths.get(cmd.getOptionValue("d")).toAbsolutePath(); } else { formatter.printHelp(formatstr, options); return; } if (!Files.exists(srcDir, LinkOption.NOFOLLOW_LINKS) || !Files.isDirectory(srcDir, LinkOption.NOFOLLOW_LINKS)) { System.out.println("[" + srcDir.toAbsolutePath() + "]??????"); return; } if (Files.exists(dstDir, LinkOption.NOFOLLOW_LINKS)) { if (!Files.isDirectory(dstDir, LinkOption.NOFOLLOW_LINKS)) { //???????? System.out.println("????????"); return; } } else { //???????? try { Files.createDirectories(dstDir); } catch (IOException e) { e.printStackTrace(); return; } } //?? if (cmd.hasOption("w") && cmd.hasOption("h")) { try { width = Integer.valueOf(cmd.getOptionValue("width")); height = Integer.valueOf(cmd.getOptionValue("height")); } catch (NumberFormatException e) { System.out.println("??????"); return; } } else { width = null; height = null; } //? if (cmd.hasOption("r")) { try { ratio = Double.valueOf(cmd.getOptionValue("r")); } catch (NumberFormatException e) { System.out.println("?????"); return; } } else { ratio = null; } if (width != null && ratio != null) { System.out.println("??????????????"); return; } if (width == null && ratio == null) { System.out.println("????????????"); return; } // int maxDepth = 1; if (cmd.hasOption("R")) { maxDepth = Integer.MAX_VALUE; } try { //Java 7 ??@see http://docs.oracle.com/javase/jp/7/api/java/nio/file/Files.html Files.walkFileTree(srcDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), maxDepth, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException { //???&??? String filename = path.getFileName().toString().toLowerCase(); if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) { //Jpeg?? /* * relative??: * rootPath: /a/b/c/d * filePath: /a/b/c/d/e/f.jpg * rootPath.relativize(filePath) = e/f.jpg */ /* * resolve?? * rootPath: /a/b/c/output * relativePath: e/f.jpg * rootPath.resolve(relativePath) = /a/b/c/output/e/f.jpg */ Path dst = dstDir.resolve(srcDir.relativize(path)); if (!Files.exists(dst.getParent(), LinkOption.NOFOLLOW_LINKS)) { Files.createDirectories(dst.getParent()); } doResize(path.toFile(), dst.toFile(), width, height, ratio); } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.ignorelist.kassandra.steam.scraper.TaggerCli.java
/** * @param args the command line arguments * @throws java.io.IOException//w ww .ja v a 2s .c o m * @throws org.antlr.runtime.RecognitionException * @throws org.apache.commons.cli.ParseException */ public static void main(String[] args) throws IOException, RecognitionException, ParseException { Options options = buildOptions(); CommandLineParser parser = new DefaultParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); } catch (ParseException pe) { System.out.println(pe.getMessage()); System.out.println(); printHelp(options); System.exit(0); return; } if (commandLine.hasOption("h")) { printHelp(options); System.exit(0); } final PathResolver pathResolver = new PathResolver(); Configuration configuration; Path configurationFile = pathResolver.findConfiguration(); if (Files.isRegularFile(configurationFile)) { configuration = Configuration.fromPropertiesFile(configurationFile); } else { configuration = new Configuration(); } configuration = toConfiguration(configuration, commandLine); //configuration.toProperties().store(System.err, null); if (!Files.isRegularFile(configurationFile)) { configuration.writeProperties(configurationFile); System.err.println( "no configuration file present, write based on CLI options: " + configurationFile.toString()); configuration.toProperties().store(System.err, null); } Set<Path> sharedConfigPaths = configuration.getSharedConfigPaths(); if (sharedConfigPaths.size() > 1 && !commandLine.hasOption("w")) { System.err.println("multiple sharedconfig.vdf available:\n" + Joiner.on("\n").join(sharedConfigPaths) + "\n, can not write to stdout. Need to specify -w or -f with a single sharedconfig.vdf"); System.exit(1); } Tagger.Options taggerOptions = Tagger.Options.fromConfiguration(configuration); final String[] removeTagsValues = commandLine.getOptionValues("remove"); if (null != removeTagsValues) { taggerOptions.setRemoveTags(Sets.newHashSet(removeTagsValues)); } Set<TagType> tagTypes = configuration.getTagTypes(); if (null == tagTypes) { System.err.println("no tag types!"); System.exit(1); } final boolean printTags = commandLine.hasOption("p"); final HtmlTagLoader htmlTagLoader = new HtmlTagLoader(pathResolver.findCachePath("html"), null == configuration.getCacheExpiryDays() ? 7 : configuration.getCacheExpiryDays()); final BatchTagLoader tagLoader = new BatchTagLoader(htmlTagLoader, configuration.getDownloadThreads()); if (true || commandLine.hasOption("v")) { tagLoader.registerEventListener(new CliEventLoggerLoaded()); } Tagger tagger = new Tagger(tagLoader); if (printTags) { Set<String> availableTags = tagger.getAvailableTags(sharedConfigPaths, taggerOptions); Joiner.on("\n").appendTo(System.out, availableTags); } else { for (Path path : sharedConfigPaths) { VdfNode tagged = tagger.tag(path, taggerOptions); if (commandLine.hasOption("w")) { Path backup = path.getParent() .resolve(path.getFileName().toString() + ".bak" + new Date().getTime()); Files.copy(path, backup, StandardCopyOption.REPLACE_EXISTING); System.err.println("backup up " + path + " to " + backup); Files.copy(new ByteArrayInputStream(tagged.toPrettyString().getBytes(StandardCharsets.UTF_8)), path, StandardCopyOption.REPLACE_EXISTING); try { Files.setPosixFilePermissions(path, SHARED_CONFIG_POSIX_PERMS); } catch (Exception e) { System.err.println(e); } System.err.println("wrote " + path); } else { System.out.println(tagged.toPrettyString()); System.err.println("pipe to file and copy to: " + path.toString()); } } } }
From source file:edu.jhu.hlt.concrete.ingesters.webposts.WebPostIngester.java
public static void main(String... args) { Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler()); if (args.length < 2) { LOGGER.info("Usage: {} {} {} {}", WebPostIngester.class.getName(), "/path/to/output/folder", "/path/to/web/.xml/file", "<additional/xml/file/paths>"); System.exit(1);// ww w . j a v a2s . c o m } Path outPath = Paths.get(args[0]); Optional.ofNullable(outPath.getParent()).ifPresent(p -> { if (!Files.exists(p)) try { Files.createDirectories(p); } catch (IOException e) { throw new UncheckedIOException(e); } }); if (!Files.isDirectory(outPath)) { LOGGER.error("Output path must be a directory."); System.exit(1); } WebPostIngester ing = new WebPostIngester(); for (int i = 1; i < args.length; i++) { Path lp = Paths.get(args[i]); LOGGER.info("On path: {}", lp.toString()); try { Communication c = ing.fromCharacterBasedFile(lp); new WritableCommunication(c).writeToFile(outPath.resolve(c.getId() + ".comm"), true); } catch (IngestException | ConcreteException e) { LOGGER.error("Caught exception during ingest on file: " + args[i], e); } } }
From source file:edu.jhu.hlt.concrete.ingesters.bolt.BoltForumPostIngester.java
public static void main(String... args) { Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler()); if (args.length < 2) { LOGGER.info("Usage: {} {} {} {}", BoltForumPostIngester.class.getName(), "/path/to/output/folder", "/path/to/bolt/.xml/file", "<additional/xml/file/paths>"); System.exit(1);//from w w w . j a va 2 s. c o m } Path outPath = Paths.get(args[0]); Optional.ofNullable(outPath.getParent()).ifPresent(p -> { if (!Files.exists(p)) try { Files.createDirectories(p); } catch (IOException e) { throw new UncheckedIOException(e); } }); if (!Files.isDirectory(outPath)) { LOGGER.error("Output path must be a directory."); System.exit(1); } BoltForumPostIngester ing = new BoltForumPostIngester(); for (int i = 1; i < args.length; i++) { Path lp = Paths.get(args[i]); LOGGER.info("On path: {}", lp.toString()); try { Communication c = ing.fromCharacterBasedFile(lp); new WritableCommunication(c).writeToFile(outPath.resolve(c.getId() + ".comm"), true); } catch (IngestException | ConcreteException e) { LOGGER.error("Caught exception during ingest on file: " + args[i], e); } } }
From source file:net.cyllene.hackerrank.downloader.HackerrankDownloader.java
public static void main(String[] args) { // Parse arguments and set up the defaults DownloaderSettings.cmd = parseArguments(args); if (DownloaderSettings.cmd.hasOption("help")) { printHelp();//from ww w . j a va 2 s. c o m System.exit(0); } if (DownloaderSettings.cmd.hasOption("verbose")) { DownloaderSettings.beVerbose = true; } /** * Output directory logic: * 1) if directory exists, ask for -f option to overwrite, quit with message * 2) if -f flag is set, check if user has access to a parent directory * 3) if no access, quit with error * 4) if everything is OK, remember the path */ String sDesiredPath = DownloaderSettings.outputDir; if (DownloaderSettings.cmd.hasOption("directory")) { sDesiredPath = DownloaderSettings.cmd.getOptionValue("d", DownloaderSettings.outputDir); } if (DownloaderSettings.beVerbose) { System.out.println("Checking output dir: " + sDesiredPath); } Path desiredPath = Paths.get(sDesiredPath); if (Files.exists(desiredPath) && Files.isDirectory(desiredPath)) { if (!DownloaderSettings.cmd.hasOption("f")) { System.out.println("I wouldn't like to overwrite existing directory: " + sDesiredPath + ", set the --force flag if you are sure. May lead to data loss, be careful."); System.exit(0); } else { System.out.println( "WARNING!" + System.lineSeparator() + "--force flag is set. Overwriting directory: " + sDesiredPath + System.lineSeparator() + "WARNING!"); } } if ((Files.exists(desiredPath) && !Files.isWritable(desiredPath)) || !Files.isWritable(desiredPath.getParent())) { System.err .println("Fatal error: " + sDesiredPath + " cannot be created or modified. Check permissions."); // TODO: use Exceptions instead of system.exit System.exit(1); } DownloaderSettings.outputDir = sDesiredPath; Integer limit = DownloaderSettings.ITEMS_TO_DOWNLOAD; if (DownloaderSettings.cmd.hasOption("limit")) { try { limit = ((Number) DownloaderSettings.cmd.getParsedOptionValue("l")).intValue(); } catch (ParseException e) { System.out.println("Incorrect limit: " + e.getMessage() + System.lineSeparator() + "Using default value: " + limit); } } Integer offset = DownloaderSettings.ITEMS_TO_SKIP; if (DownloaderSettings.cmd.hasOption("offset")) { try { offset = ((Number) DownloaderSettings.cmd.getParsedOptionValue("o")).intValue(); } catch (ParseException e) { System.out.println("Incorrect offset: " + e.getMessage() + " Using default value: " + offset); } } DownloaderCore dc = DownloaderCore.INSTANCE; List<HRChallenge> challenges = new LinkedList<>(); // Download everything first Map<String, List<Integer>> structure = null; try { structure = dc.getStructure(offset, limit); } catch (IOException e) { System.err.println("Fatal Error: could not get data structure."); e.printStackTrace(); System.exit(1); } challengesLoop: for (Map.Entry<String, List<Integer>> entry : structure.entrySet()) { String challengeSlug = entry.getKey(); HRChallenge currentChallenge = null; try { currentChallenge = dc.getChallengeDetails(challengeSlug); } catch (IOException e) { System.err.println("Error: could not get challenge info for: " + challengeSlug); if (DownloaderSettings.beVerbose) { e.printStackTrace(); } continue challengesLoop; } submissionsLoop: for (Integer submissionId : entry.getValue()) { HRSubmission submission = null; try { submission = dc.getSubmissionDetails(submissionId); } catch (IOException e) { System.err.println("Error: could not get submission info for: " + submissionId); if (DownloaderSettings.beVerbose) { e.printStackTrace(); } continue submissionsLoop; } // TODO: probably should move filtering logic elsewhere(getStructure, maybe) if (submission.getStatus().equalsIgnoreCase("Accepted")) { currentChallenge.getSubmissions().add(submission); } } challenges.add(currentChallenge); } // Now dump all data to disk try { for (HRChallenge currentChallenge : challenges) { if (currentChallenge.getSubmissions().isEmpty()) continue; final String sChallengePath = DownloaderSettings.outputDir + "/" + currentChallenge.getSlug(); final String sSolutionPath = sChallengePath + "/accepted_solutions"; final String sDescriptionPath = sChallengePath + "/problem_description"; Files.createDirectories(Paths.get(sDescriptionPath)); Files.createDirectories(Paths.get(sSolutionPath)); // FIXME: this should be done the other way String plainBody = currentChallenge.getDescriptions().get(0).getBody(); String sFname; if (!plainBody.equals("null")) { sFname = sDescriptionPath + "/english.txt"; if (DownloaderSettings.beVerbose) { System.out.println("Writing to: " + sFname); } Files.write(Paths.get(sFname), plainBody.getBytes(StandardCharsets.UTF_8.name())); } String htmlBody = currentChallenge.getDescriptions().get(0).getBodyHTML(); String temporaryHtmlTemplate = "<html></body>" + htmlBody + "</body></html>"; sFname = sDescriptionPath + "/english.html"; if (DownloaderSettings.beVerbose) { System.out.println("Writing to: " + sFname); } Files.write(Paths.get(sFname), temporaryHtmlTemplate.getBytes(StandardCharsets.UTF_8.name())); for (HRSubmission submission : currentChallenge.getSubmissions()) { sFname = String.format("%s/%d.%s", sSolutionPath, submission.getId(), submission.getLanguage()); if (DownloaderSettings.beVerbose) { System.out.println("Writing to: " + sFname); } Files.write(Paths.get(sFname), submission.getSourceCode().getBytes(StandardCharsets.UTF_8.name())); } } } catch (IOException e) { System.err.println("Fatal Error: couldn't dump data to disk."); System.exit(1); } }
From source file:org.codice.ddf.admin.configurator.impl.ConfigValidator.java
private static void protectEtcDir(Path target) { if (target.getParent().endsWith("etc")) { throw new IllegalArgumentException("Invalid attempt to edit system file in /etc directory"); }/*from w w w . ja v a 2 s .c o m*/ }
From source file:fi.jumi.launcher.daemon.DirBasedSteward.java
private static void copyToFile(InputStream source, Path destination) throws IOException { Files.createDirectories(destination.getParent()); try (OutputStream out = Files.newOutputStream(destination)) { IOUtils.copy(source, out);//from w ww . j av a2s . co m } }