List of usage examples for java.io File mkdir
public boolean mkdir()
From source file:me.rgcjonas.portableMinecraftLauncher.Main.java
/** * entry point//from w w w .ja va2 s . c o m * @param args */ public static void main(String[] args) { File workDir = getWorkingDirectory(); //ensure the working directory exists if (!workDir.exists()) { workDir.mkdir(); } File launcherJar = new File(workDir, "launcher.jar"); //download launcher if it doesn't exist if (!launcherJar.exists()) { try { URL launcherurl = new URL("https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft.jar"); FileUtils.copyURLToFile(launcherurl, launcherJar); } catch (IOException e) { // shouldn't happen e.printStackTrace(); } } URL[] urls; try { urls = new URL[] { launcherJar.toURI().toURL() }; //this class loader mustn't be disposed while the launcher is running @SuppressWarnings("resource") LauncherClassLoader loader = new LauncherClassLoader(urls); //run it Class<?> launcherFrame = loader.loadClass("net.minecraft.LauncherFrame"); launcherFrame.getMethod("main", String[].class).invoke(null, (Object) args); } catch (Exception e) { // there's nothing we can do in that case but notify the dev e.printStackTrace(); } }
From source file:Main.java
public static void main(String[] args) { File workingDirectory = new File("C:" + File.separator + "Invoices"); File template = new File(workingDirectory.getAbsolutePath() + File.separator + "invoiceTemplate.tex"); File tempDir = new File(workingDirectory.getAbsolutePath() + File.separator + "temp"); if (!tempDir.isDirectory()) { tempDir.mkdir(); }/*from w w w .jav a2s . c o m*/ File invoice1 = new File(tempDir.getAbsolutePath() + File.separator + "invoice1.tex"); File invoice2 = new File(tempDir.getAbsolutePath() + File.separator + "invoice2.tex"); try { HashMap<String, String> data = new HashMap<String, String>(); data.put("Number", "1"); data.put("Customer name", "Ivan Pfeiffer"); data.put("Customer street", "Schwarzer Weg 4"); data.put("Customer zip", "13505 Berlin"); data.put("Development", "Software"); data.put("Price", "500"); JLRConverter converter = new JLRConverter("::", ":::"); if (!converter.parse(template, invoice1, data)) { System.out.println(converter.getErrorMessage()); } data.put("Number", "2"); data.put("Customer name", "Mike Mueller"); data.put("Customer street", "Prenzlauer Berg 12"); data.put("Customer zip", "10405 Berlin"); data.put("Development", "Hardware"); data.put("Price", "2350"); if (!converter.parse(template, invoice2, data)) { System.out.println(converter.getErrorMessage()); } File desktop = new File(System.getProperty("user.home") + File.separator + "Desktop"); JLRGenerator pdfGen = new JLRGenerator(); pdfGen.deleteTempTexFile(false); if (!pdfGen.generate(invoice1, desktop, workingDirectory)) { System.out.println(pdfGen.getErrorMessage()); } JLROpener.open(pdfGen.getPDF()); if (!pdfGen.generate(invoice2, desktop, workingDirectory)) { System.out.println(pdfGen.getErrorMessage()); } JLROpener.open(pdfGen.getPDF()); } catch (IOException ex) { System.err.println(ex.getMessage()); } }
From source file:eu.annocultor.converters.geonames.GeonamesDumpToRdf.java
public static void main(String[] args) throws Exception { File root = new File("input_source"); // load country-continent match countryToContinent//from w w w . jav a 2 s . c o m .load((new GeonamesDumpToRdf()).getClass().getResourceAsStream("/country-to-continent.properties")); // creating files Map<String, BufferedWriter> files = new HashMap<String, BufferedWriter>(); Map<String, Boolean> started = new HashMap<String, Boolean>(); for (Object string : countryToContinent.keySet()) { String continent = countryToContinent.getProperty(string.toString()); File dir = new File(root, continent); if (!dir.exists()) { dir.mkdir(); } files.put(string.toString(), new BufferedWriter(new OutputStreamWriter( new FileOutputStream(new File(root, continent + "/" + string + ".rdf")), "UTF-8"))); System.out.println(continent + "/" + string + ".rdf"); started.put(string.toString(), false); } System.out.println(started); Pattern countryPattern = Pattern .compile("<inCountry rdf\\:resource\\=\"http\\://www\\.geonames\\.org/countries/\\#(\\w\\w)\"/>"); long counter = 0; LineIterator it = FileUtils.lineIterator(new File(root, "all-geonames-rdf.txt"), "UTF-8"); try { while (it.hasNext()) { String text = it.nextLine(); if (text.startsWith("http://sws.geonames")) continue; // progress counter++; if (counter % 100000 == 0) { System.out.print("*"); } // System.out.println(counter); // get country String country = null; Matcher matcher = countryPattern.matcher(text); if (matcher.find()) { country = matcher.group(1); } // System.out.println(country); if (country == null) country = "null"; text = text.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><rdf:RDF", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><rdf:RDF"); if (started.get(country) == null) throw new Exception("Unknow country " + country); if (started.get(country).booleanValue()) { // remove RDF opening text = text.substring(text.indexOf("<rdf:RDF ")); text = text.substring(text.indexOf(">") + 1); } // remove RDF ending text = text.substring(0, text.indexOf("</rdf:RDF>")); files.get(country).append(text + "\n"); if (!started.get(country).booleanValue()) { // System.out.println("Started with country " + country); } started.put(country, true); } } finally { LineIterator.closeQuietly(it); } for (Object string : countryToContinent.keySet()) { boolean hasStarted = started.get(string.toString()).booleanValue(); if (hasStarted) { BufferedWriter bf = files.get(string.toString()); bf.append("</rdf:RDF>"); bf.flush(); bf.close(); } } return; }
From source file:at.co.malli.relpm.RelPM.java
/** * @param args the command line arguments *//* w ww . ja va2s .co m*/ 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> }
From source file:copi.ScalaEntryPoint.java
public static void main(String[] args) { /*/* ww w. j a va2 s . c o m*/ * Set lwjgl library path so that LWJGL finds the natives depending on * the OS. */ File libDir = new File(path); if (!libDir.exists()) { // create native lib folder libDir.mkdir(); // retrieve os type String osName = System.getProperty("os.name"); // try to determine if the system is 64 bit boolean is64bit = false; if (System.getProperty("os.name").contains("Windows")) { is64bit = (System.getenv("ProgramFiles(x86)") != null); } else { is64bit = (System.getProperty("os.arch").indexOf("64") != -1); } // construct name of native lib file String natLibLWJGL = ""; if (osName.startsWith("Windows")) { natLibLWJGL += "lwjgl"; if (is64bit) natLibLWJGL += "64"; natLibLWJGL += ".dll"; } else if (osName.startsWith("Linux")) { natLibLWJGL += "liblwjgl"; if (is64bit) natLibLWJGL += "64"; natLibLWJGL += ".so"; } else if (osName.startsWith("Mac OS X")) { natLibLWJGL += "liblwjgl"; natLibLWJGL += ".jnilib"; } else { System.out.println("Unsupported OS: " + osName + ". Exiting."); System.exit(-1); } // try to establish an input stream on the native lib inside the jar InputStream fis = ScalaEntryPoint.class.getResourceAsStream("/" + natLibLWJGL); if (fis == null) { System.out.println("Native library file " + natLibLWJGL + " was not found inside JAR."); System.exit(-1); } // establish an output stream on the target file File fOut = new File(path + "/" + natLibLWJGL); try (FileOutputStream fos = new FileOutputStream(fOut)) { // create file at destination if not already existing if (!fOut.exists()) fOut.createNewFile(); // making buffer for copy operation byte[] buffer = new byte[1024]; int readBytes; // Open output stream and copy data between source file in JAR and the temporary file try { while ((readBytes = fis.read(buffer)) != -1) { fos.write(buffer, 0, readBytes); } } finally { fos.close(); fis.close(); } } catch (IOException e) { System.out.println(e.getMessage()); System.exit(-1); } // register shutdown hook JVMShutdownHook jvmShutdownHook = new JVMShutdownHook(); Runtime.getRuntime().addShutdownHook(jvmShutdownHook); } // set lwjgl native library path System.setProperty("org.lwjgl.librarypath", libDir.getAbsolutePath()); // start COPI System.out.println("Starting COPI ..."); (new SICApplicationLogic()).render(); }
From source file:com.mmounirou.spotirss.SpotiRss.java
/** * @param args/*from w w w.j av a2 s . c o m*/ * @throws IOException * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException * @throws SpotifyClientException * @throws ChartRssException * @throws SpotifyException */ public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SpotifyClientException { if (args.length == 0) { System.err.println("usage : java -jar spotiboard.jar <charts-folder>"); return; } Properties connProperties = new Properties(); InputStream inStream = SpotiRss.class.getResourceAsStream("/spotify-server.properties"); try { connProperties.load(inStream); } finally { IOUtils.closeQuietly(inStream); } String host = connProperties.getProperty("host"); int port = Integer.parseInt(connProperties.getProperty("port")); String user = connProperties.getProperty("user"); final SpotifyClient spotifyClient = new SpotifyClient(host, port, user); final Map<String, Playlist> playlistsByTitle = getPlaylistsByTitle(spotifyClient); final File outputDir = new File(args[0]); outputDir.mkdirs(); TrackCache cache = new TrackCache(); try { for (String strProvider : PROVIDERS) { String providerClassName = EntryToTrackConverter.class.getPackage().getName() + "." + StringUtils.capitalize(strProvider); final EntryToTrackConverter converter = (EntryToTrackConverter) SpotiRss.class.getClassLoader() .loadClass(providerClassName).newInstance(); Iterable<String> chartsRss = getCharts(strProvider); final File resultDir = new File(outputDir, strProvider); resultDir.mkdir(); final SpotifyHrefQuery hrefQuery = new SpotifyHrefQuery(cache); Iterable<String> results = FluentIterable.from(chartsRss).transform(new Function<String, String>() { @Override @Nullable public String apply(@Nullable String chartRss) { try { long begin = System.currentTimeMillis(); ChartRss bilboardChartRss = ChartRss.getInstance(chartRss, converter); Map<Track, String> trackHrefs = hrefQuery.getTrackHrefs(bilboardChartRss.getSongs()); String strTitle = bilboardChartRss.getTitle(); File resultFile = new File(resultDir, strTitle); List<String> lines = Lists.newLinkedList(FluentIterable.from(trackHrefs.keySet()) .transform(Functions.toStringFunction())); lines.addAll(trackHrefs.values()); FileUtils.writeLines(resultFile, Charsets.UTF_8.displayName(), lines); Playlist playlist = playlistsByTitle.get(strTitle); if (playlist != null) { playlist.getTracks().clear(); playlist.getTracks().addAll(trackHrefs.values()); spotifyClient.patch(playlist); LOGGER.info(String.format("%s chart exported patched", strTitle)); } LOGGER.info(String.format("%s chart exported in %s in %d s", strTitle, resultFile.getAbsolutePath(), (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - begin))); } catch (Exception e) { LOGGER.error(String.format("fail to export %s charts", chartRss), e); } return ""; } }); // consume iterables Iterables.size(results); } } finally { cache.close(); } }
From source file:com.github.rnewson.couchdb.lucene.Main.java
/** * Run couchdb-lucene./*from w w w .ja v a 2 s . c om*/ */ 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:eu.digitisation.idiomaident.utils.CorpusFilter.java
public static void main(String args[]) { if (args.length < 2) { System.err.println("Usage: CorpusFilter" + "inFolder outFolder"); } else {//from ww w. j a va 2 s . c o m File inFile = new File(args[0]); File outFile = new File(args[1]); if (inFile.exists() && inFile.isDirectory()) { if (!outFile.exists()) { outFile.mkdir(); } CorpusFilter.filter(inFile, outFile, "es"); } } }
From source file:net.itransformers.bgpPeeringMap.BgpPeeringMapFromFile.java
public static void main(String[] args) throws Exception { Map<String, String> params = CmdLineParser.parseCmdLine(args); logger.info("input params" + params.toString()); final String settingsFile = params.get("-s"); if (settingsFile == null) { printUsage("bgpPeeringMap.properties"); return;//from w ww . j a v a 2 s .c o m } Map<String, String> settings = loadProperties(new File(System.getProperty("base.dir"), settingsFile)); logger.info("Settings" + settings.toString()); File outputDir = new File(System.getProperty("base.dir"), settings.get("output.dir")); System.out.println(outputDir.getAbsolutePath()); boolean result = outputDir.mkdir(); // if (!result) { // System.out.println("result:"+result); // System.out.println("Unable to create dir: "+outputDir); // return; // } File graphmlDir = new File(outputDir, settings.get("output.dir.graphml")); result = outputDir.mkdir(); // if (!result) { // System.out.println("Unable to create dir: "+graphmlDir); // return; // } XsltTransformer transformer = new XsltTransformer(); byte[] rawData = readRawDataFile(settings.get("raw-data-file")); logger.info("First-transformation has started with xsltTransformator " + settings.get("xsltFileName1")); ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(); File xsltFileName1 = new File(System.getProperty("base.dir"), settings.get("xsltFileName1")); ByteArrayInputStream inputStream1 = new ByteArrayInputStream(rawData); // transformer.transformXML(inputStream1, xsltFileName1, outputStream1, settings); logger.info("First transformation finished"); File outputFile1 = new File(graphmlDir, "bgpPeeringMap-intermediate.xml"); FileUtils.writeStringToFile(outputFile1, new String(outputStream1.toByteArray())); logger.info("Second transformation started with xsltTransformator " + settings.get("xsltFileName2")); ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream(); File xsltFileName2 = new File(System.getProperty("base.dir"), settings.get("xsltFileName2")); ByteArrayInputStream inputStream2 = new ByteArrayInputStream(outputStream1.toByteArray()); // transformer.transformXML(inputStream2, xsltFileName2, outputStream2, settings); logger.info("Second transformation finished"); File outputFile = new File(graphmlDir, "bgpPeeringMap.graphml"); File nodesFileListFile = new File(graphmlDir, "nodes-file-list.txt"); FileUtils.writeStringToFile(outputFile, new String(outputStream2.toByteArray())); logger.info("Output Graphml saved in a file in" + graphmlDir); FileUtils.writeStringToFile(nodesFileListFile, "bgpPeeringMap.graphml"); ByteArrayInputStream inputStream3 = new ByteArrayInputStream(outputStream2.toByteArray()); ByteArrayOutputStream outputStream3 = new ByteArrayOutputStream(); File xsltFileName3 = new File(System.getProperty("base.dir"), settings.get("xsltFileName3")); // transformer.transformXML(inputStream3, xsltFileName3, outputStream3); }
From source file:com.galois.fiveui.HeadlessRunner.java
/** * @param args list of headless run description filenames * @throws IOException// ww w .j a v a 2 s. c om * @throws URISyntaxException * @throws ParseException */ @SuppressWarnings("static-access") public static void main(final String[] args) throws IOException, URISyntaxException, ParseException { // Setup command line options Options options = new Options(); Option help = new Option("h", "print this help message"); Option output = OptionBuilder.withArgName("outfile").hasArg().withDescription("write output to file") .create("o"); Option report = OptionBuilder.withArgName("report directory").hasArg() .withDescription("write HTML reports to given directory").create("r"); options.addOption(output); options.addOption(report); options.addOption("v", false, "verbose output"); options.addOption("vv", false, "VERY verbose output"); options.addOption(help); // Parse command line options CommandLineParser parser = new GnuParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Command line option parsing failed. Reason: " + e.getMessage()); System.exit(1); } // Display help if requested if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("headless <input file 1> [<input file 2> ...]", options); System.exit(1); } // Set logging levels BasicConfigurator.configure(); Logger fiveuiLogger = Logger.getLogger("com.galois.fiveui"); Logger rootLogger = Logger.getRootLogger(); if (cmd.hasOption("v")) { fiveuiLogger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.ERROR); } else if (cmd.hasOption("vv")) { fiveuiLogger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.DEBUG); } else { fiveuiLogger.setLevel(Level.ERROR); rootLogger.setLevel(Level.ERROR); } // Setup output file if requested PrintWriter outStream = null; if (cmd.hasOption("o")) { String outfile = cmd.getOptionValue("o"); try { outStream = new PrintWriter(new BufferedWriter(new FileWriter(outfile))); } catch (IOException e) { System.err.println("Could not open outfile for writing: " + cmd.getOptionValue("outfile")); System.exit(1); } } else { outStream = new PrintWriter(new BufferedWriter(new PrintWriter(System.out))); } // Setup HTML reports directory before the major work happens in case we // have to throw an exception. PrintWriter summaryFile = null; PrintWriter byURLFile = null; PrintWriter byRuleFile = null; if (cmd.hasOption("r")) { String repDir = cmd.getOptionValue("r"); try { File file = new File(repDir); if (!file.exists()) { file.mkdir(); logger.info("report directory created: " + repDir); } else { logger.info("report directory already exists!"); } summaryFile = new PrintWriter(new FileWriter(repDir + File.separator + "summary.html")); byURLFile = new PrintWriter(new FileWriter(repDir + File.separator + "byURL.html")); byRuleFile = new PrintWriter(new FileWriter(repDir + File.separator + "byRule.html")); } catch (IOException e) { System.err.println("could not open report directory / files for writing"); System.exit(1); } } // Major work: process input files ImmutableList<Result> results = null; for (String in : cmd.getArgs()) { HeadlessRunDescription descr = HeadlessRunDescription.parse(in); logger.debug("invoking headless run..."); BatchRunner runner = new BatchRunner(); results = runner.runHeadless(descr); logger.debug("runHeadless returned " + results.size() + " results"); // write results to the output stream as we go for (Result result : results) { outStream.println(result.toString()); } outStream.flush(); } outStream.close(); // Write report files if requested if (cmd.hasOption("r") && results != null) { Reporter kermit = new Reporter(results); summaryFile.write(kermit.getSummary()); summaryFile.close(); byURLFile.write(kermit.getByURL()); byURLFile.close(); byRuleFile.write(kermit.getByRule()); byRuleFile.close(); } }