Example usage for java.io File getParentFile

List of usage examples for java.io File getParentFile

Introduction

In this page you can find the example usage for java.io File getParentFile.

Prototype

public File getParentFile() 

Source Link

Document

Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.

Usage

From source file:cn.dreampie.FileUtilities.java

public static void main(String[] args) {
    //    System.out.println(FileUtilities.getCommaSeparatedListOfFileNames(directoryToFileList("/home/ice/IdeaProjects/icedog/src/main/")));
    File file = new File("/home/ice/IdeaProjects/icedog/src/main/webapp/javascript/min/a.js");
    System.out.println(file.getParentFile().mkdir());
}

From source file:be.redlab.maven.yamlprops.create.YamlConvertCli.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    HelpFormatter formatter = new HelpFormatter();
    options.addOption(Option.builder("s").argName("source").desc("the source folder or file to convert")
            .longOpt("source").hasArg(true).build());
    options.addOption(Option.builder("t").argName("target").desc("the target file to store in")
            .longOpt("target").hasArg(true).build());
    options.addOption(Option.builder("h").desc("print help").build());

    try {//from w w w.ja v a 2 s .co m
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            formatter.printHelp("converter", options);
        }
        File source = new File(cmd.getOptionValue("s", System.getProperty("user.dir")));
        String name = source.getName();
        if (source.isDirectory()) {
            PropertiesToYamlConverter yamlConverter = new PropertiesToYamlConverter();
            String[] ext = { "properties" };
            Iterator<File> fileIterator = FileUtils.iterateFiles(source, ext, true);
            while (fileIterator.hasNext()) {
                File next = fileIterator.next();
                System.out.println(next);
                String s = StringUtils.removeStart(next.getParentFile().getPath(), source.getPath());
                System.out.println(s);
                String f = StringUtils.split(s, IOUtils.DIR_SEPARATOR)[0];
                System.out.println("key = " + f);
                Properties p = new Properties();
                try {
                    p.load(new FileReader(next));
                    yamlConverter.addProperties(f, p);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            yamlConverter.writeYaml(fileWriter);
            fileWriter.close();
        } else {
            Properties p = new Properties();
            p.load(new FileReader(source));
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            new PropertiesToYamlConverter().addProperties(name, p).writeYaml(fileWriter);
            fileWriter.close();
        }
    } catch (ParseException e) {
        e.printStackTrace();
        formatter.printHelp("converter", options);
    }
}

From source file:net.minecraftforge.fml.common.patcher.GenDiffSet.java

public static void main(String[] args) throws IOException {
    String sourceJar = args[0]; //Clean Vanilla jar minecraft.jar or minecraft_server.jar
    String targetDir = args[1]; //Directory containing obfed output classes, typically mcp/reobf/minecraft
    String deobfData = args[2]; //Path to FML's deobfusication_data.lzma
    String outputDir = args[3]; //Path to place generated .binpatch
    String killTarget = args[4]; //"true" if we should destroy the target file if it generated a successful .binpatch

    LogManager.getLogger("GENDIFF").log(Level.INFO,
            String.format("Creating patches at %s for %s from %s", outputDir, sourceJar, targetDir));
    Delta delta = new Delta();
    FMLDeobfuscatingRemapper remapper = FMLDeobfuscatingRemapper.INSTANCE;
    remapper.setupLoadOnly(deobfData, false);
    JarFile sourceZip = new JarFile(sourceJar);
    boolean kill = killTarget.equalsIgnoreCase("true");

    File f = new File(outputDir);
    f.mkdirs();//from   w  ww. jav  a  2 s  . c  o  m

    for (String name : remapper.getObfedClasses()) {
        //            Logger.getLogger("GENDIFF").info(String.format("Evaluating path for data :%s",name));
        String fileName = name;
        String jarName = name;
        if (RESERVED_NAMES.contains(name.toUpperCase(Locale.ENGLISH))) {
            fileName = "_" + name;
        }
        File targetFile = new File(targetDir, fileName.replace('/', File.separatorChar) + ".class");
        jarName = jarName + ".class";
        if (targetFile.exists()) {
            String sourceClassName = name.replace('/', '.');
            String targetClassName = remapper.map(name).replace('/', '.');
            JarEntry entry = sourceZip.getJarEntry(jarName);
            byte[] vanillaBytes = toByteArray(sourceZip, entry);
            byte[] patchedBytes = Files.toByteArray(targetFile);

            byte[] diff = delta.compute(vanillaBytes, patchedBytes);

            ByteArrayDataOutput diffOut = ByteStreams.newDataOutput(diff.length + 50);
            // Original name
            diffOut.writeUTF(name);
            // Source name
            diffOut.writeUTF(sourceClassName);
            // Target name
            diffOut.writeUTF(targetClassName);
            // exists at original
            diffOut.writeBoolean(entry != null);
            if (entry != null) {
                diffOut.writeInt(Hashing.adler32().hashBytes(vanillaBytes).asInt());
            }
            // length of patch
            diffOut.writeInt(diff.length);
            // patch
            diffOut.write(diff);

            File target = new File(outputDir, targetClassName + ".binpatch");
            target.getParentFile().mkdirs();
            Files.write(diffOut.toByteArray(), target);
            Logger.getLogger("GENDIFF").info(String.format("Wrote patch for %s (%s) at %s", name,
                    targetClassName, target.getAbsolutePath()));
            if (kill) {
                targetFile.delete();
                Logger.getLogger("GENDIFF").info(String.format("  Deleted target: %s", targetFile.toString()));
            }
        }
    }
    sourceZip.close();
}

From source file:jhc.redsniff.generation.PackageScanningGenerator.java

public static void main(String[] args) throws Exception {

    if (args.length != 5) {
        System.err.println("Args: source-dir package-class-filter parent-class generated-class output-dir");
        System.err.println("");
        System.err.println("    source-dir  : Path to Java source containing matchers to generate sugar for.");
        System.err.println("                  May contain multiple paths, separated by commas.");
        System.err.println("                  e.g. src/java,src/more-java");
        System.err.println(//from   w  ww  .  j ava  2  s.c  o m
                "    package-class-filter  : base of package to look for classes with methods, eg jhc.selenium.matchers");

        System.err.println("");
        System.err.println(
                "parent-class : Full name of parent class type to examine - eg org.hamcrest.Matcher, jhc.selenium.seeker.Seeker");
        System.err.println("                  e.g. org.myproject.MyMatchers");
        System.err.println("generated-class : Full name of class to generate.");
        System.err.println("                  e.g. org.myproject.MyMatchers");
        System.err.println("");
        System.err.println("     output-dir : Where to output generated code (package subdirs will be");
        System.err.println("                  automatically created).");
        System.err.println("                  e.g. build/generated-code");
        System.exit(-1);
    }

    String srcDirs = args[0];
    String package_name_prefix = args[1];
    String parentClassName = args[2];
    String fullClassName = args[3];
    File outputDir = new File(args[4]);

    String fileName = fullClassName.replace('.', File.separatorChar) + ".java";
    int dotIndex = fullClassName.lastIndexOf(".");
    String packageName = dotIndex == -1 ? "" : fullClassName.substring(0, dotIndex);
    String shortClassName = fullClassName.substring(dotIndex + 1);

    if (!outputDir.isDirectory()) {
        System.err.println("Output directory not found : " + outputDir.getAbsolutePath());
        System.exit(-1);
    }

    Class<?> parentClass = Class.forName(parentClassName);

    File outputFile = new File(outputDir, fileName);
    outputFile.getParentFile().mkdirs();
    File tmpFile = new File(outputDir, fileName + ".tmp");

    SugarGenerator sugarGenerator = new SugarGenerator();
    try {
        sugarGenerator
                .addWriter(new SeleniumFactoryWriter(packageName, shortClassName, new FileWriter(tmpFile)));
        sugarGenerator.addWriter(new QuickReferenceWriter(System.out));

        PackageScanningGenerator pkgScanningGenerator = new PackageScanningGenerator(sugarGenerator,
                PackageScanningGenerator.class.getClassLoader(), parentClass);

        if (srcDirs.trim().length() > 0) {
            for (String srcDir : srcDirs.split(",")) {
                pkgScanningGenerator.addSourceDir(new File(srcDir));
            }
        }
        // could add use of xml just to list filter expressions
        // pkgScanningGenerator.load(new InputSource(configFile));
        pkgScanningGenerator.addClasses(package_name_prefix);

        System.out.println("Generating " + fullClassName);
        sugarGenerator.generate();
        sugarGenerator.close();
        outputFile.delete();
        FileUtils.moveFile(tmpFile, outputFile);

    } finally {
        tmpFile.delete();
        sugarGenerator.close();
    }
}

From source file:org.kuali.student.git.importer.GitImporterMain.java

/**
 * @param args//from  ww  w .j a va 2 s  .c o m
 */
public static void main(final String[] args) {

    if (args.length != 8 && args.length != 9) {
        log.error(
                "USAGE: <svn dump file> <git repository> <veto.log> <skipped-copy-from.log> <blob.log> <gc enabled> <svn repo base url> <repo uuid> [<git command path>]");
        log.error("\t<veto.log> : which paths were veto's as not being a valid branch");
        log.error("\t<skipped-copy-from.log> : which copy-from-paths were skipped");
        log.error("\t<blob.log> : issues related to blobs (typically directory copy related)");
        log.error("\t<gc enabled> : set to 1 (true ever 500 revs) or 0 (false) to disable");
        log.error("\t<svn repo base url> : the svn repo base url to use in the git-svn-id");
        log.error(
                "\t<repo uuid> : The svn repository uuid to use in the git-svn-id.\n\tIt you are importing from a clone use this to set the field to the real repositories uuid.");
        log.error("\t<git command path> : the path to a native git to use for gc's which occur every 500 revs");
        System.exit(-1);
    }

    try {

        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "GitImporterMain-applicationContext.xml");

        applicationContext.registerShutdownHook();

        SvnDumpFilter filter = applicationContext.getBean(SvnDumpFilter.class);

        BranchDetector branchDetector = applicationContext.getBean("branchDetector", BranchDetector.class);

        // final MergeDetectorData detectorData = applicationContext
        // .getBean(MergeDetectorData.class);

        File dumpFile = new File(args[0]);

        if (!dumpFile.exists()) {
            throw new FileNotFoundException(args[0] + " path not found");
        }

        File gitRepository = new File(args[1]).getAbsoluteFile();

        if (!gitRepository.getParentFile().exists())
            throw new FileNotFoundException(args[1] + "path not found");

        final PrintWriter vetoLog = new PrintWriter(args[2]);

        final PrintWriter copyFromSkippedLog = new PrintWriter(args[3]);

        final PrintWriter blobLog = new PrintWriter(args[4]);

        boolean gcEnabled = true;

        final boolean printGitSvnIds = true; // not optional anymore

        String repositoryBaseUrl = null;

        String repositoryUUID = null;

        if (args[5].trim().equals("0"))
            gcEnabled = false;

        repositoryBaseUrl = args[6].trim();

        repositoryUUID = args[7].trim();

        String nativeGitCommandPath = null;

        if (args.length == 9)
            nativeGitCommandPath = args[8].trim();

        final Repository repo = GitRepositoryUtils.buildFileRepository(gitRepository, false);

        // extract any known branches from the repository

        BZip2CompressorInputStream compressedInputStream = new BZip2CompressorInputStream(
                new FileInputStream(dumpFile));

        filter.parseDumpFile(compressedInputStream,
                new GitImporterParseOptions(repo, vetoLog, copyFromSkippedLog, blobLog, printGitSvnIds,
                        repositoryBaseUrl, repositoryUUID, branchDetector, gcEnabled, nativeGitCommandPath));

        vetoLog.close();
        copyFromSkippedLog.close();
        blobLog.close();

        compressedInputStream.close();

    } catch (Exception e) {
        log.error("Processing failed", e);
    }

}

From source file:fr.cs.examples.propagation.VisibilityCircle.java

/** Program entry point.
 * @param args program arguments/*from   ww w  .  ja  va 2s .c o  m*/
 */
public static void main(String[] args) {
    try {

        // configure Orekit
        Autoconfiguration.configureOrekit();

        // input/out
        File input = new File(VisibilityCircle.class.getResource("/visibility-circle.in").toURI().getPath());
        File output = new File(input.getParentFile(), "visibility-circle.csv");

        new VisibilityCircle().run(input, output, ",");

        System.out.println("visibility circle saved as file " + output);

    } catch (URISyntaxException use) {
        System.err.println(use.getLocalizedMessage());
        System.exit(1);
    } catch (IOException ioe) {
        System.err.println(ioe.getLocalizedMessage());
        System.exit(1);
    } catch (IllegalArgumentException iae) {
        System.err.println(iae.getLocalizedMessage());
        System.exit(1);
    } catch (OrekitException oe) {
        System.err.println(oe.getLocalizedMessage());
        System.exit(1);
    }
}

From source file:com.nuance.expertassistant.ContentCrawler.java

public static void main(String args[]) {
    if (args.length == 0) {
        ContentExtractor.startDocument("Test3", "/Users/abhishek_rohatgi/" + "Test3" + ".xml");
        ContentExtractor.extract("http://www.audihelp.com/auda-147-tyre_repairs.html");
        ContentExtractor.endDocument();/*from w w  w.j a  v a 2s.com*/
    } else {
        final ContentCrawlerOptions options = new ContentCrawlerOptions(args);
        final ContentCrawlerInputTypes inputType = ContentCrawlerOptions.getInputType();
        if (ContentCrawlerInputTypes.FILE.equals(inputType)) {
            final File outputFile = new File(getOutput());
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }
            translateFile(getInput(), getOutput());
        } else if (ContentCrawlerInputTypes.FOLDER.equals(inputType)) {
            final File outputFolder = new File(getOutput());
            final Collection<File> inputFiles = FileUtils.listFiles(new File(getInput()),
                    new RegexFileFilter("^(.*\\.(html)?)"), DirectoryFileFilter.DIRECTORY);
            for (final File inputFile : inputFiles) {
                final String outputFileName = inputFile.getAbsolutePath().substring(getInput().length())
                        + ".xml";
                final File outputFile = new File(outputFolder, outputFileName);
                if (!outputFile.getParentFile().exists()) {
                    outputFile.getParentFile().mkdirs();
                }
                translateFile(inputFile.getAbsolutePath(), outputFile.getAbsolutePath());
            }

        } else {
            ContentExtractor.startDocument(getInput(), getOutput());
            ContentExtractor.extract(getInput());
            ContentExtractor.endDocument();
        }
    }
}

From source file:com.ctriposs.rest4j.tools.data.FilterSchemaGenerator.java

public static void main(String[] args) {
    final CommandLineParser parser = new GnuParser();
    CommandLine cl = null;/* w  w w.ja va2 s.  c  om*/
    try {
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        _log.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final String[] directoryArgs = cl.getArgs();
    if (directoryArgs.length != 2) {
        reportInvalidArguments();
    }

    final File sourceDirectory = new File(directoryArgs[0]);
    if (!sourceDirectory.exists()) {
        _log.error(sourceDirectory.getPath() + " does not exist");
        System.exit(1);
    }
    if (!sourceDirectory.isDirectory()) {
        _log.error(sourceDirectory.getPath() + " is not a directory");
        System.exit(1);
    }
    final URI sourceDirectoryURI = sourceDirectory.toURI();

    final File outputDirectory = new File(directoryArgs[1]);
    if (outputDirectory.exists() && !sourceDirectory.isDirectory()) {
        _log.error(outputDirectory.getPath() + " is not a directory");
        System.exit(1);
    }

    final boolean isAvroMode = cl.hasOption('a');
    final String predicateExpression = cl.getOptionValue('e');
    final Predicate predicate = PredicateExpressionParser.parse(predicateExpression);

    final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null);
    int exitCode = 0;
    for (File sourceFile : sourceFiles) {
        try {
            final ValidationOptions val = new ValidationOptions();
            val.setAvroUnionMode(isAvroMode);

            final SchemaParser schemaParser = new SchemaParser();
            schemaParser.setValidationOptions(val);

            schemaParser.parse(new FileInputStream(sourceFile));
            if (schemaParser.hasError()) {
                _log.error("Error parsing " + sourceFile.getPath() + ": "
                        + schemaParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0);
            if (!(originalSchema instanceof NamedDataSchema)) {
                _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema");
                exitCode = 1;
                continue;
            }

            final SchemaParser filterParser = new SchemaParser();
            filterParser.setValidationOptions(val);

            final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema,
                    predicate, filterParser);
            if (filterParser.hasError()) {
                _log.error("Error applying predicate: " + filterParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath();
            final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath;
            final File outputFile = new File(outputFilePath);
            final File outputFileParent = outputFile.getParentFile();
            outputFileParent.mkdirs();
            if (!outputFileParent.exists()) {
                _log.error("Unable to write filtered schema to " + outputFileParent.getPath());
                exitCode = 1;
                continue;
            }

            FileOutputStream fout = new FileOutputStream(outputFile);
            fout.write(filteredSchema.toString().getBytes(RestConstants.DEFAULT_CHARSET));
            fout.close();
        } catch (IOException e) {
            _log.error(e.getMessage());
            exitCode = 1;
        }
    }

    System.exit(exitCode);
}

From source file:com.linkedin.restli.tools.data.FilterSchemaGenerator.java

public static void main(String[] args) {
    CommandLine cl = null;//from ww  w .  j a v  a 2s.c  om
    try {
        final CommandLineParser parser = new GnuParser();
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        _log.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final String[] directoryArgs = cl.getArgs();
    if (directoryArgs.length != 2) {
        reportInvalidArguments();
    }

    final File sourceDirectory = new File(directoryArgs[0]);
    if (!sourceDirectory.exists()) {
        _log.error(sourceDirectory.getPath() + " does not exist");
        System.exit(1);
    }
    if (!sourceDirectory.isDirectory()) {
        _log.error(sourceDirectory.getPath() + " is not a directory");
        System.exit(1);
    }
    final URI sourceDirectoryURI = sourceDirectory.toURI();

    final File outputDirectory = new File(directoryArgs[1]);
    if (outputDirectory.exists() && !sourceDirectory.isDirectory()) {
        _log.error(outputDirectory.getPath() + " is not a directory");
        System.exit(1);
    }

    final boolean isAvroMode = cl.hasOption('a');
    final String predicateExpression = cl.getOptionValue('e');
    final Predicate predicate = PredicateExpressionParser.parse(predicateExpression);

    final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null);
    int exitCode = 0;
    for (File sourceFile : sourceFiles) {
        try {
            final ValidationOptions val = new ValidationOptions();
            val.setAvroUnionMode(isAvroMode);

            final SchemaParser schemaParser = new SchemaParser();
            schemaParser.setValidationOptions(val);

            schemaParser.parse(new FileInputStream(sourceFile));
            if (schemaParser.hasError()) {
                _log.error("Error parsing " + sourceFile.getPath() + ": " + schemaParser.errorMessageBuilder());
                exitCode = 1;
                continue;
            }

            final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0);
            if (!(originalSchema instanceof NamedDataSchema)) {
                _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema");
                exitCode = 1;
                continue;
            }

            final SchemaParser filterParser = new SchemaParser();
            filterParser.setValidationOptions(val);

            final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema,
                    predicate, filterParser);
            if (filterParser.hasError()) {
                _log.error("Error applying predicate: " + filterParser.errorMessageBuilder());
                exitCode = 1;
                continue;
            }

            final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath();
            final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath;
            final File outputFile = new File(outputFilePath);
            final File outputFileParent = outputFile.getParentFile();
            outputFileParent.mkdirs();
            if (!outputFileParent.exists()) {
                _log.error("Unable to write filtered schema to " + outputFileParent.getPath());
                exitCode = 1;
                continue;
            }

            FileOutputStream fout = new FileOutputStream(outputFile);
            String schemaJson = SchemaToJsonEncoder.schemaToJson(filteredSchema, JsonBuilder.Pretty.INDENTED);
            fout.write(schemaJson.getBytes(RestConstants.DEFAULT_CHARSET));
            fout.close();
        } catch (IOException e) {
            _log.error(e.getMessage());
            exitCode = 1;
        }
    }

    System.exit(exitCode);
}

From source file:com.l2jfree.tools.ProjectSettingsSynchronizer.java

public static void main(String[] args) throws IOException {
    final File src = new File(".").getCanonicalFile();
    System.out.println("Copying from: " + src);
    System.out.println();//ww  w .  jav  a2  s .  c  om

    final List<File> destinations = new ArrayList<File>();
    for (File dest : src.getParentFile().listFiles()) {
        if (dest.isHidden() || !dest.isDirectory())
            continue;

        destinations.add(dest);
        System.out.println("Copying to: " + dest);
    }
    System.out.println();

    // .project
    System.out.println(".project");
    System.out.println("================================================================================");
    {
        final List<String> lines = FileUtils.readLines(new File(src, ".project"));

        for (File dest : destinations) {
            lines.set(2, lines.get(2).replaceAll(src.getName(), dest.getName()));
            writeLines(dest, ".project", lines);
            lines.set(2, lines.get(2).replaceAll(dest.getName(), src.getName()));
        }
    }
    System.out.println();

    // .classpath
    System.out.println(".classpath");
    System.out.println("================================================================================");
    {
        final List<String> lines = FileUtils.readLines(new File(src, ".classpath"));

        for (File dest : destinations) {
            if (dest.getName().endsWith("-main") || dest.getName().endsWith("-datapack")) {
                final ArrayList<String> tmp = new ArrayList<String>();

                for (String line : lines)
                    if (!line.contains("classpathentry"))
                        tmp.add(line);

                writeLines(dest, ".classpath", tmp);
                continue;
            }

            writeLines(dest, ".classpath", lines);
        }
    }
    System.out.println();

    // .settings
    System.out.println(".settings");
    System.out.println("================================================================================");
    for (File settingsFile : new File(src, ".settings").listFiles()) {
        if (settingsFile.getName().endsWith(".prefs")) {
            System.out.println(".settings/" + settingsFile.getName());
            System.out.println(
                    "--------------------------------------------------------------------------------");

            final List<String> lines = FileUtils.readLines(settingsFile);

            if (lines.get(0).startsWith("#"))
                lines.remove(0);

            for (File dest : destinations) {
                writeLines(new File(dest, ".settings"), settingsFile.getName(), lines);
            }
            System.out.println();
        }
    }
    System.out.println();
}