Example usage for java.io File canWrite

List of usage examples for java.io File canWrite

Introduction

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

Prototype

public boolean canWrite() 

Source Link

Document

Tests whether the application can modify the file denoted by this abstract pathname.

Usage

From source file:FileDemo.java

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

    // Display constants
    System.out.println("pathSeparatorChar = " + File.pathSeparatorChar);
    System.out.println("separatorChar = " + File.separatorChar);

    // Test some methods
    File file = new File(args[0]);
    System.out.println("getName() = " + file.getName());
    System.out.println("getParent() = " + file.getParent());
    System.out.println("getAbsolutePath() = " + file.getAbsolutePath());
    System.out.println("getCanonicalPath() = " + file.getCanonicalPath());
    System.out.println("getPath() = " + file.getPath());
    System.out.println("canRead() = " + file.canRead());
    System.out.println("canWrite() = " + file.canWrite());
}

From source file:PKCS12Import.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("usage: java PKCS12Import {pkcs12file} [newjksfile]");
        System.exit(1);/*from   w  ww  . j a  v a2s.c  o m*/
    }

    File fileIn = new File(args[0]);
    File fileOut;
    if (args.length > 1) {
        fileOut = new File(args[1]);
    } else {
        fileOut = new File("newstore.jks");
    }

    if (!fileIn.canRead()) {
        System.err.println("Unable to access input keystore: " + fileIn.getPath());
        System.exit(2);
    }

    if (fileOut.exists() && !fileOut.canWrite()) {
        System.err.println("Output file is not writable: " + fileOut.getPath());
        System.exit(2);
    }

    KeyStore kspkcs12 = KeyStore.getInstance("pkcs12");
    KeyStore ksjks = KeyStore.getInstance("jks");

    System.out.print("Enter input keystore passphrase: ");
    char[] inphrase = readPassphrase();
    System.out.print("Enter output keystore passphrase: ");
    char[] outphrase = readPassphrase();

    kspkcs12.load(new FileInputStream(fileIn), inphrase);

    ksjks.load((fileOut.exists()) ? new FileInputStream(fileOut) : null, outphrase);

    Enumeration eAliases = kspkcs12.aliases();
    int n = 0;
    while (eAliases.hasMoreElements()) {
        String strAlias = (String) eAliases.nextElement();
        System.err.println("Alias " + n++ + ": " + strAlias);

        if (kspkcs12.isKeyEntry(strAlias)) {
            System.err.println("Adding key for alias " + strAlias);
            Key key = kspkcs12.getKey(strAlias, inphrase);

            Certificate[] chain = kspkcs12.getCertificateChain(strAlias);

            ksjks.setKeyEntry(strAlias, key, outphrase, chain);
        }
    }

    OutputStream out = new FileOutputStream(fileOut);
    ksjks.store(out, outphrase);
    out.close();
}

From source file:edu.ucdenver.ccp.nlp.ae.dict_util.GeneInfoToDictionary.java

public static void main(String args[]) {

    BasicConfigurator.configure();/*from   w w w  .  j a  va  2s  . c  om*/

    if (args.length < 2) {
        usage();
    } else {
        try {
            File geneFile = new File(args[0]);
            File outputFile = new File(args[1]);
            if (!geneFile.canRead()) {
                System.out.println("can't read input file;" + geneFile.getAbsolutePath());
                usage();
                System.exit(-2);
            }
            if (outputFile.exists() && !outputFile.canWrite()) {
                System.out.println("can't write output file;" + outputFile.getAbsolutePath());
                usage();
                System.exit(-3);
            }

            logger.warn("running with: " + geneFile.getAbsolutePath());
            GeneInfoToDictionary converter = new GeneInfoToDictionary(geneFile);
            converter.convert(geneFile, outputFile);
        } catch (Exception e) {
            System.out.println("error:" + e);
            e.printStackTrace();
            System.exit(-1);
        }
    }
}

From source file:com.github.rnewson.couchdb.lucene.Main.java

/**
 * Run couchdb-lucene.//w  w w . ja  va  2 s.  c  o  m
 */
public static void main(String[] args) throws Exception {
    final HierarchicalINIConfiguration configuration = new HierarchicalINIConfiguration(
            Main.class.getClassLoader().getResource("couchdb-lucene.ini"));
    configuration.setReloadingStrategy(new FileChangedReloadingStrategy());

    final File dir = new File(configuration.getString("lucene.dir", "indexes"));

    if (dir == null) {
        LOG.error("lucene.dir not set.");
        System.exit(1);
    }
    if (!dir.exists() && !dir.mkdir()) {
        LOG.error("Could not create " + dir.getCanonicalPath());
        System.exit(1);
    }
    if (!dir.canRead()) {
        LOG.error(dir + " is not readable.");
        System.exit(1);
    }
    if (!dir.canWrite()) {
        LOG.error(dir + " is not writable.");
        System.exit(1);
    }
    LOG.info("Index output goes to: " + dir.getCanonicalPath());

    final Server server = new Server();
    final SelectChannelConnector connector = new SelectChannelConnector();
    connector.setHost(configuration.getString("lucene.host", "localhost"));
    connector.setPort(configuration.getInt("lucene.port", 5985));

    LOG.info("Accepting connections with " + connector);

    server.setConnectors(new Connector[] { connector });
    server.setStopAtShutdown(true);
    server.setSendServerVersion(false);

    HttpClientFactory.setIni(configuration);
    final HttpClient httpClient = HttpClientFactory.getInstance();

    final LuceneServlet servlet = new LuceneServlet(httpClient, dir, configuration);

    final Context context = new Context(server, "/", Context.NO_SESSIONS | Context.NO_SECURITY);
    context.addServlet(new ServletHolder(servlet), "/*");
    context.addFilter(new FilterHolder(new GzipFilter()), "/*", Handler.DEFAULT);
    context.setErrorHandler(new JSONErrorHandler());
    server.setHandler(context);

    server.start();
    server.join();
}

From source file:com.ibm.jaql.MiniCluster.java

/**
 * @param args/*from   www.ja  va  2  s.  c  om*/
 */
public static void main(String[] args) throws IOException {
    String clusterHome = System.getProperty("hadoop.minicluster.dir");
    if (clusterHome == null) {
        clusterHome = "./minicluster";
        System.setProperty("hadoop.minicluster.dir", clusterHome);
    }
    LOG.info("hadoop.minicluster.dir=" + clusterHome);
    File clusterFile = new File(clusterHome);
    if (!clusterFile.exists()) {
        clusterFile.mkdirs();
    }
    if (!clusterFile.isDirectory()) {
        throw new IOException("minicluster home directory must be a directory: " + clusterHome);
    }
    if (!clusterFile.canRead() || !clusterFile.canWrite()) {
        throw new IOException("minicluster home directory must be readable and writable: " + clusterHome);
    }

    String logDir = System.getProperty("hadoop.log.dir");
    if (logDir == null) {
        logDir = clusterHome + File.separator + "logs";
        System.setProperty("hadoop.log.dir", logDir);
    }
    File logFile = new File(logDir);
    if (!logFile.exists()) {
        logFile.mkdirs();
    }

    String confDir = System.getProperty("hadoop.conf.override");
    if (confDir == null) {
        confDir = clusterHome + File.separator + "conf";
        System.setProperty("hadoop.conf.override", confDir);
    }
    File confFile = new File(confDir);
    if (!confFile.exists()) {
        confFile.mkdirs();
    }

    System.out.println("starting minicluster in " + clusterHome);
    MiniCluster mc = new MiniCluster(args);
    // To find the ports in the 
    // hdfs: search for: Web-server up at: localhost:####
    // mapred: search for: mapred.JobTracker: JobTracker webserver: ####
    Configuration conf = mc.getConf();
    System.out.println("fs.default.name: " + conf.get("fs.default.name"));
    System.out.println("dfs.http.address: " + conf.get("dfs.http.address"));
    System.out.println("mapred.job.tracker.http.address: " + conf.get("mapred.job.tracker.http.address"));

    boolean waitForInterrupt;
    try {
        System.out.println("press enter to end minicluster (or eof to run forever)...");
        waitForInterrupt = System.in.read() < 0; // wait for any input or eof
    } catch (Exception e) {
        // something odd happened.  Just shutdown. 
        LOG.error("error reading from stdin", e);
        waitForInterrupt = false;
    }

    // eof means that we will wait for a kill signal
    while (waitForInterrupt) {
        System.out.println("minicluster is running until interrupted...");
        try {
            Thread.sleep(60 * 60 * 1000);
        } catch (InterruptedException e) {
            waitForInterrupt = false;
        }
    }

    System.out.println("shutting down minicluster...");
    try {
        mc.tearDown();
    } catch (Exception e) {
        LOG.error("error while shutting down minicluster", e);
    }
}

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

public static void main(String[] args) {
    // check &   validate cmdline options
    OptionGroup opt_g = getCMDLineOptionsGroups();
    Options opt = getCMDLineOptions();//w  w  w.  j  av a  2s.co  m
    opt.addOptionGroup(opt_g);

    CommandLineParser cli = new DefaultParser();
    try {
        CommandLine cl = cli.parse(opt, args);

        if (cl.hasOption("v")) {
            VerboseOutputFilter.SHOW_VERBOSE = true;
        }

        switch (opt_g.getSelected()) {
        case "V":
            try {
                URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation();
                String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8");
                JarFile jarFile = new JarFile(jarPath);
                Manifest m = jarFile.getManifest();
                StringBuilder versionInfo = new StringBuilder();
                for (Object key : m.getMainAttributes().keySet()) {
                    versionInfo.append(key).append(":").append(m.getMainAttributes().getValue(key.toString()))
                            .append("\n");
                }
                System.out.println(versionInfo.toString());
            } catch (Exception e) {
                log.error("Version info could not be read.");
            }
            break;
        case "h":
            HelpFormatter help = new HelpFormatter();
            String header = ""; //TODO: missing infotext 
            StringBuilder footer = new StringBuilder("Supported configuration properties :");
            help.printHelp("CodeGen -h | -V | -g  [...]", header, opt, footer.toString());
            break;
        case "g":
            // target dir
            if (cl.hasOption("t")) {
                File target = new File(cl.getOptionValue("t"));
                if (target.isDirectory() && target.canExecute() && target.canWrite()) {
                    config.setProperty("target.dir", cl.getOptionValue("t"));
                } else {
                    log.error("Target dir '{}' is inaccessible!", cl.getOptionValue("t"));
                    break;
                }
            } else {
                config.setProperty("target.dir", System.getProperty("java.io.tmpdir"));
            }

            // project dir
            if (cl.hasOption("p")) {
                File project = new File(cl.getOptionValue("p"));
                if (!project.exists()) {
                    if (!project.mkdirs()) {
                        log.error("Project dir '{}' can't be created!", cl.getOptionValue("p"));
                        break;
                    }
                }

                if (project.isDirectory() && project.canExecute() && project.canWrite()) {
                    config.setProperty("project.dir", cl.getOptionValue("p"));
                } else {
                    log.error("Project dir '{}' is inaccessible!", cl.getOptionValue("p"));
                    break;
                }
            }

            generateAppfromXML(cl.getOptionValue("g"));
            break;
        }
    } catch (ParseException e) {
        log.error("ParseException occurred while parsing cmdline arguments!\n{}", e.getLocalizedMessage());
    }

}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.LuceneIndexer.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption(CommonParams.ROOT_DIR_PARAM, null, true, CommonParams.ROOT_DIR_DESC);
    options.addOption(CommonParams.SUB_DIR_TYPE_PARAM, null, true, CommonParams.SUB_DIR_TYPE_DESC);
    options.addOption(CommonParams.MAX_NUM_REC_PARAM, null, true, CommonParams.MAX_NUM_REC_DESC);
    options.addOption(CommonParams.SOLR_FILE_NAME_PARAM, null, true, CommonParams.SOLR_FILE_NAME_DESC);
    options.addOption(CommonParams.OUT_INDEX_PARAM, null, true, CommonParams.OUT_MINDEX_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {/* w  w w  . j  a va 2  s  . c o  m*/
        CommandLine cmd = parser.parse(options, args);

        String rootDir = null;

        rootDir = cmd.getOptionValue(CommonParams.ROOT_DIR_PARAM);

        if (null == rootDir)
            Usage("Specify: " + CommonParams.ROOT_DIR_DESC, options);

        String outputDirName = cmd.getOptionValue(CommonParams.OUT_INDEX_PARAM);

        if (null == outputDirName)
            Usage("Specify: " + CommonParams.OUT_MINDEX_DESC, options);

        String subDirTypeList = cmd.getOptionValue(CommonParams.SUB_DIR_TYPE_PARAM);

        if (null == subDirTypeList || subDirTypeList.isEmpty())
            Usage("Specify: " + CommonParams.SUB_DIR_TYPE_DESC, options);

        String solrFileName = cmd.getOptionValue(CommonParams.SOLR_FILE_NAME_PARAM);
        if (null == solrFileName)
            Usage("Specify: " + CommonParams.SOLR_FILE_NAME_DESC, options);

        int maxNumRec = Integer.MAX_VALUE;

        String tmp = cmd.getOptionValue(CommonParams.MAX_NUM_REC_PARAM);

        if (tmp != null) {
            try {
                maxNumRec = Integer.parseInt(tmp);
                if (maxNumRec <= 0) {
                    Usage("The maximum number of records should be a positive integer", options);
                }
            } catch (NumberFormatException e) {
                Usage("The maximum number of records should be a positive integer", options);
            }
        }

        File outputDir = new File(outputDirName);
        if (!outputDir.exists()) {
            if (!outputDir.mkdirs()) {
                System.out.println("couldn't create " + outputDir.getAbsolutePath());
                System.exit(1);
            }
        }
        if (!outputDir.isDirectory()) {
            System.out.println(outputDir.getAbsolutePath() + " is not a directory!");
            System.exit(1);
        }
        if (!outputDir.canWrite()) {
            System.out.println("Can't write to " + outputDir.getAbsolutePath());
            System.exit(1);
        }

        String subDirs[] = subDirTypeList.split(",");

        int docNum = 0;

        // No English analyzer here, all language-related processing is done already,
        // here we simply white-space tokenize and index tokens verbatim.
        Analyzer analyzer = new WhitespaceAnalyzer();
        FSDirectory indexDir = FSDirectory.open(outputDir);
        IndexWriterConfig indexConf = new IndexWriterConfig(analyzer.getVersion(), analyzer);

        System.out.println("Creating a new Lucene index, maximum # of docs to process: " + maxNumRec);
        indexConf.setOpenMode(OpenMode.CREATE);
        IndexWriter indexWriter = new IndexWriter(indexDir, indexConf);

        for (int subDirId = 0; subDirId < subDirs.length && docNum < maxNumRec; ++subDirId) {
            String inputFileName = rootDir + "/" + subDirs[subDirId] + "/" + solrFileName;

            System.out.println("Input file name: " + inputFileName);

            BufferedReader inpText = new BufferedReader(
                    new InputStreamReader(CompressUtils.createInputStream(inputFileName)));
            String docText = XmlHelper.readNextXMLIndexEntry(inpText);

            for (; docText != null && docNum < maxNumRec; docText = XmlHelper.readNextXMLIndexEntry(inpText)) {
                ++docNum;
                Map<String, String> docFields = null;

                Document luceneDoc = new Document();

                try {
                    docFields = XmlHelper.parseXMLIndexEntry(docText);
                } catch (Exception e) {
                    System.err.println(String.format("Parsing error, offending DOC #%d:\n%s", docNum, docText));
                    System.exit(1);
                }

                String id = docFields.get(UtilConst.TAG_DOCNO);

                if (id == null) {
                    System.err.println(String.format("No ID tag '%s', offending DOC #%d:\n%s",
                            UtilConst.TAG_DOCNO, docNum, docText));
                }

                luceneDoc.add(new StringField(UtilConst.TAG_DOCNO, id, Field.Store.YES));

                for (Map.Entry<String, String> e : docFields.entrySet())
                    if (!e.getKey().equals(UtilConst.TAG_DOCNO)) {
                        luceneDoc.add(new TextField(e.getKey(), e.getValue(), Field.Store.YES));
                    }
                indexWriter.addDocument(luceneDoc);
                if (docNum % 1000 == 0)
                    System.out.println("Indexed " + docNum + " docs");
            }
            System.out.println("Indexed " + docNum + " docs");
        }

        indexWriter.commit();
        indexWriter.close();

    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:edu.ucdenver.ccp.nlp.ae.dict_util.OboToDictionary.java

public static void main(String args[]) {

        BasicConfigurator.configure();//w w w  . j  av a 2s  .  c  om

        if (args.length < 2) {
            usage();
        } else {
            try {
                File oboFile = new File(args[0]);
                File outputFile = new File(args[1]);
                String namespaceName = "";
                if (args.length > 2) {
                    namespaceName = args[2];
                }
                if (!oboFile.canRead()) {
                    System.out.println("can't read input file;" + oboFile.getAbsolutePath());
                    usage();
                    System.exit(-2);
                }
                if (outputFile.exists() && !outputFile.canWrite()) {
                    System.out.println("can't write output file;" + outputFile.getAbsolutePath());
                    usage();
                    System.exit(-3);
                }

                logger.warn("running with: " + oboFile.getAbsolutePath());
                OboToDictionary converter = null;
                if (namespaceName != null && namespaceName.length() > 0) {
                    Set<String> namespaceSet = new TreeSet<String>();
                    namespaceSet.add(namespaceName);
                    converter = new OboToDictionary(true, SynonymType.EXACT_ONLY, namespaceSet);
                } else {
                    converter = new OboToDictionary();
                }
                converter.convert(oboFile, outputFile);
            } catch (Exception e) {
                System.out.println("error:" + e);
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }

From source file:com.junoyoon.BullsHtml.java

/**
 * @param args/*from   www.  j a v  a 2  s.  c o  m*/
 */
public static void main(String[] args) {
    final CommandLineParser clp = new DefaultParser();
    CommandLine line = null;

    // parse CLI options
    try {
        line = clp.parse(BullsHtml.OPTS, args);
    } catch (ParseException e) {
        printMessage("Invalid options");
        usage();
        return;
    }
    String sourceEncoding = BullsHtml.enc;
    // get encoding option
    if (line.hasOption("e")) {
        sourceEncoding = line.getOptionValue("e");
    }
    // print usage if -h
    if (line.hasOption("h")) {
        usage();
    }

    if (line.hasOption("v")) {
        BullsHtml.verbose = true;
    }
    String covfile = null;
    if (line.hasOption("f")) {
        covfile = line.getOptionValue("f");
        if (!new File(covfile).exists()) {
            printErrorAndExit(covfile + " does not exists");
        }
    }

    String outputPath = ".";

    if (line.getArgs().length != 1) {
        printErrorAndExit("please provide the html output directory");
    }
    outputPath = line.getArgs()[0];
    File o = new File(outputPath);
    if (!o.exists()) {
        if (!o.mkdirs()) {
            printErrorAndExit(outputPath + " directory can be not created.");
        }
    } else if (!o.isDirectory()) {
        printErrorAndExit(outputPath + " is not directory.");
    } else if (!o.canWrite()) {
        printErrorAndExit(outputPath + " is not writable.");
    }
    BullsHtml bullshtml = new BullsHtml();
    bullshtml.process(covfile);
    if (BullsHtml.baseList.isEmpty()) {
        printErrorAndExit(
                "No coverage was recorded in cov file. please check if src is compiled with coverage on.");
    }
    try {
        bullshtml.copyResources(outputPath);
    } catch (Exception e) {
        printErrorAndExit("The output " + outputPath + " is not writable.", e);
    }
    BullsHtml.sourceEncoding = Encoding.getEncoding(sourceEncoding);
    bullshtml.generateHtml(o);
    bullshtml.generateCloverXml(o);
}

From source file:at.co.malli.relpm.RelPM.java

/**
 * @param args the command line arguments
 *//*from w  w w  . j  a  v a2  s.  c  om*/
public static void main(String[] args) {
    //<editor-fold defaultstate="collapsed" desc=" Create config & log directory ">
    String userHome = System.getProperty("user.home");
    File relPm = new File(userHome + "/.RelPM");
    if (!relPm.exists()) {
        boolean worked = relPm.mkdir();
        if (!worked) {
            ExceptionDisplayer.showErrorMessage(new Exception("Could not create directory "
                    + relPm.getAbsolutePath() + " to store user-settings and logs"));
            System.exit(-1);
        }
    }
    File userConfig = new File(relPm.getAbsolutePath() + "/RelPM-userconfig.xml"); //should be created...
    if (!userConfig.exists()) {
        try {
            URL resource = RelPM.class.getResource("/at/co/malli/relpm/RelPM-defaults.xml");
            FileUtils.copyURLToFile(resource, userConfig);
        } catch (IOException ex) {
            ExceptionDisplayer.showErrorMessage(new Exception("Could not copy default config. Reason:\n"
                    + ex.getClass().getName() + ": " + ex.getMessage()));
            System.exit(-1);
        }
    }
    if (!userConfig.canWrite() || !userConfig.canRead()) {
        ExceptionDisplayer.showErrorMessage(new Exception(
                "Can not read or write " + userConfig.getAbsolutePath() + "to store user-settings"));
        System.exit(-1);
    }
    if (System.getProperty("os.name").toLowerCase().contains("win")) {
        Path relPmPath = Paths.get(relPm.toURI());
        try {
            Files.setAttribute(relPmPath, "dos:hidden", true);
        } catch (IOException ex) {
            ExceptionDisplayer.showErrorMessage(new Exception("Could not set " + relPm.getAbsolutePath()
                    + " hidden. " + "Reason:\n" + ex.getClass().getName() + ": " + ex.getMessage()));
            System.exit(-1);
        }
    }
    //</editor-fold>

    logger.trace("Environment setup sucessfull");

    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code ">
    try {
        String wantedLookAndFeel = SettingsProvider.getInstance().getString("gui.lookAndFeel");
        UIManager.LookAndFeelInfo[] installed = UIManager.getInstalledLookAndFeels();
        boolean found = false;
        for (UIManager.LookAndFeelInfo info : installed) {
            if (info.getClassName().equals(wantedLookAndFeel))
                found = true;
        }
        if (found)
            UIManager.setLookAndFeel(wantedLookAndFeel);
        else
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    } catch (InstantiationException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    } catch (IllegalAccessException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Add GUI start to awt EventQue ">
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MainGUI().setVisible(true);
        }
    });
    //</editor-fold>
}