List of usage examples for java.io FileWriter FileWriter
public FileWriter(FileDescriptor fd)
From source file:com.npower.dm.util.ConvertMailProfile.java
/** * @param args/*from w w w . j a v a 2s .c o m*/ */ public static void main(String[] args) throws Exception { File outputFile = new File("c:/temp/mail.xml"); FileWriter writer = new FileWriter(outputFile); File csvFile = new File("c:/temp/mail.csv"); BufferedReader reader = new BufferedReader(new FileReader(csvFile)); String line = reader.readLine(); while (line != null) { line = reader.readLine(); if (StringUtils.isEmpty(line)) { continue; } String[] cols = StringUtils.split(line, ','); Map<String, String> values = new HashMap<String, String>(); values.put("name", cols[0]); values.put("smtp.host", cols[1]); values.put("pop.host", cols[2]); writeXML(writer, values); } writer.close(); reader.close(); }
From source file:PodbaseMetadataMigration2.java
public static void main(String[] args) throws Exception { System.out.println("Running data migration"); String projectString = FileUtils.readFileToString(new File("projects.txt")); Map<String, Integer> projectIdMapping = new HashMap<String, Integer>(); for (String line : projectString.split("\n")) { String[] split = line.split(":"); int id = Integer.parseInt(split[0].trim()); String name = split[1].trim(); projectIdMapping.put(name, id);//from www .j a va 2s . co m } System.out.println("Reading projects.."); List<ProjectEntry> projects = dataFromFile("./migrate/projects.data", ProjectEntry.class); projectIdMap = parseProjectMap(projects, projectIdMapping); System.out.println("Found " + projects.size() + " projects."); System.out.println("Reading tags.."); List<TagEntry> tags = dataFromFile("./migrate/tags.data", TagEntry.class); System.out.println("Found " + tags.size() + " tags."); System.out.println("Reading templates.."); List<TemplateEntry> templates = dataFromFile("./migrate/templates.data", TemplateEntry.class); System.out.println("Found " + templates.size() + " templates."); System.out.println("Reading template fields.."); List<TemplateFieldEntry> templateFields = dataFromFile("./migrate/template_fields.data", TemplateFieldEntry.class); System.out.println("Found " + templateFields.size() + " templateFields."); int entryCount = tags.size() + templates.size() + templateFields.size(); //System.out.println("Generating Project SQL"); //String projectSql = generateSql((List<AbstractEntry>)(List<?>)projects); System.out.println("Generating Attribute SQL"); String imageAttributes = generateSql((List<AbstractEntry>) (List<?>) tags); System.out.println("Generating Image SQL"); String databaseImages = generateDatabaseImageSql(); //System.out.println("Generating Directory SQL"); //String directorySql = generateDirectorySql(projects); //System.out.println("Generating Template SQL"); //String templateSql = generateSql((List<AbstractEntry>)(List<?>)templates); //System.out.println("Generating Field SQL"); //String fieldsSql = generateSql((List<AbstractEntry>)(List<?>)templateFields); System.out.println("Writing database.sql"); BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./database.sql"))); //bw.append(projectSql); //bw.append("\n\n"); bw.append(databaseImages); bw.append("\n\n"); //bw.append(directorySql); //bw.append("\n\n"); bw.append(imageAttributes); bw.append("\n\n"); // bw.append(templateSql); // bw.append("\n\n"); // bw.append(fieldsSql); // bw.append("\n\n"); bw.close(); System.out.println("Writing missingImages.txt"); bw = new BufferedWriter(new FileWriter(new File("./missingImages.txt"))); for (String img : missingImages) { bw.append(img + "\n"); } bw.close(); System.out.println("Migration completed successfully!"); }
From source file:com.linkedin.pinotdruidbenchmark.PinotResponseTime.java
public static void main(String[] args) throws Exception { if (args.length != 4 && args.length != 5) { System.err.println(//from w ww .j ava2 s . c om "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional)."); return; } File queryDir = new File(args[0]); String resourceUrl = args[1]; int warmUpRounds = Integer.parseInt(args[2]); int testRounds = Integer.parseInt(args[3]); File resultDir; if (args.length == 4) { resultDir = null; } else { resultDir = new File(args[4]); if (!resultDir.exists()) { if (!resultDir.mkdirs()) { throw new RuntimeException("Failed to create result directory: " + resultDir); } } } File[] queryFiles = queryDir.listFiles(); assert queryFiles != null; Arrays.sort(queryFiles); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(resourceUrl); for (File queryFile : queryFiles) { String query = new BufferedReader(new FileReader(queryFile)).readLine(); httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}")); System.out.println( "--------------------------------------------------------------------------------"); System.out.println("Running query: " + query); System.out.println( "--------------------------------------------------------------------------------"); // Warm-up Rounds System.out.println("Run " + warmUpRounds + " times to warm up..."); for (int i = 0; i < warmUpRounds; i++) { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.close(); System.out.print('*'); } System.out.println(); // Test Rounds System.out.println("Run " + testRounds + " times to get response time statistics..."); long[] responseTimes = new long[testRounds]; long totalResponseTime = 0L; for (int i = 0; i < testRounds; i++) { long startTime = System.currentTimeMillis(); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.close(); long responseTime = System.currentTimeMillis() - startTime; responseTimes[i] = responseTime; totalResponseTime += responseTime; System.out.print(responseTime + "ms "); } System.out.println(); // Store result. if (resultDir != null) { File resultFile = new File(resultDir, queryFile.getName() + ".result"); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); try (BufferedInputStream bufferedInputStream = new BufferedInputStream( httpResponse.getEntity().getContent()); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) { int length; while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) { bufferedWriter.write(new String(BYTE_BUFFER, 0, length)); } } httpResponse.close(); } // Process response times. double averageResponseTime = (double) totalResponseTime / testRounds; double temp = 0; for (long responseTime : responseTimes) { temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime); } double standardDeviation = Math.sqrt(temp / testRounds); System.out.println("Average response time: " + averageResponseTime + "ms"); System.out.println("Standard deviation: " + standardDeviation); } } }
From source file:com.chargebee.Application.MappingHeaders.java
public static void main(String[] args) throws Exception { String source1 = System.getProperty("user.home") + "/Output-3.csv"; // Source CSV file containing the customer details String source2 = System.getProperty("user.home") + "/header.json";//Json file containing the customer id and token String output = System.getProperty("user.home") + "/Output-4.csv";// The destination CSV file. // Scanner sc = new Scanner(System.in); // System.out.println("Input CSV File: "); // String source1 = sc.nextLine(); ////from ww w . j ava 2 s . c om // System.out.println("config File: "); // String source2 = sc.nextLine(); // // System.out.println("Output CSV File: "); // String output = sc.nextLine(); // MappingHeaders objHm = new MappingHeaders(); JSONObject jobj = objHm.readJsonData(source2); CSVPrinter printer = new CSVPrinter(new FileWriter(output), CSVFormat.EXCEL.withRecordSeparator("\n").withDelimiter(',')); CSVParser parser = new CSVParser(new FileReader(source1), CSVFormat.EXCEL.withHeader()); objHm.extractJsonData(jobj, printer, parser); parser.close(); printer.close(); }
From source file:com.tamingtext.tagging.LuceneTagExtractor.java
public static void main(String[] args) throws IOException { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option inputOpt = obuilder.withLongName("dir").withRequired(true) .withArgument(abuilder.withName("dir").withMinimum(1).withMaximum(1).create()) .withDescription("The Lucene directory").withShortName("d").create(); Option outputOpt = obuilder.withLongName("output").withRequired(false) .withArgument(abuilder.withName("output").withMinimum(1).withMaximum(1).create()) .withDescription("The output directory").withShortName("o").create(); Option maxOpt = obuilder.withLongName("max").withRequired(false) .withArgument(abuilder.withName("max").withMinimum(1).withMaximum(1).create()) .withDescription(//from w w w. ja va2 s. c om "The maximum number of vectors to output. If not specified, then it will loop over all docs") .withShortName("m").create(); Option fieldOpt = obuilder.withLongName("field").withRequired(true) .withArgument(abuilder.withName("field").withMinimum(1).withMaximum(1).create()) .withDescription("The field in the index").withShortName("f").create(); Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h") .create(); Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(outputOpt).withOption(maxOpt) .withOption(fieldOpt).create(); try { Parser parser = new Parser(); parser.setGroup(group); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } File file = new File(cmdLine.getValue(inputOpt).toString()); if (!file.isDirectory()) { throw new IllegalArgumentException(file + " does not exist or is not a directory"); } long maxDocs = Long.MAX_VALUE; if (cmdLine.hasOption(maxOpt)) { maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString()); } if (maxDocs < 0) { throw new IllegalArgumentException("maxDocs must be >= 0"); } String field = cmdLine.getValue(fieldOpt).toString(); PrintWriter out = null; if (cmdLine.hasOption(outputOpt)) { out = new PrintWriter(new FileWriter(cmdLine.getValue(outputOpt).toString())); } else { out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")); } File output = new File("/home/drew/taming-text/delicious/training"); output.mkdirs(); emitTextForTags(file, output); IOUtils.close(Collections.singleton(out)); } catch (OptionException e) { log.error("Exception", e); CommandLineUtil.printHelp(group); } }
From source file:com.tamingtext.tagging.LuceneCategoryExtractor.java
public static void main(String[] args) throws IOException { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option inputOpt = obuilder.withLongName("dir").withRequired(true) .withArgument(abuilder.withName("dir").withMinimum(1).withMaximum(1).create()) .withDescription("The Lucene directory").withShortName("d").create(); Option outputOpt = obuilder.withLongName("output").withRequired(false) .withArgument(abuilder.withName("output").withMinimum(1).withMaximum(1).create()) .withDescription("The output directory").withShortName("o").create(); Option maxOpt = obuilder.withLongName("max").withRequired(false) .withArgument(abuilder.withName("max").withMinimum(1).withMaximum(1).create()) .withDescription(/* w ww . jav a 2 s . c o m*/ "The maximum number of documents to analyze. If not specified, then it will loop over all docs") .withShortName("m").create(); Option fieldOpt = obuilder.withLongName("field").withRequired(true) .withArgument(abuilder.withName("field").withMinimum(1).withMaximum(1).create()) .withDescription("The field in the index").withShortName("f").create(); Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h") .create(); Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(outputOpt).withOption(maxOpt) .withOption(fieldOpt).create(); try { Parser parser = new Parser(); parser.setGroup(group); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } File inputDir = new File(cmdLine.getValue(inputOpt).toString()); if (!inputDir.isDirectory()) { throw new IllegalArgumentException(inputDir + " does not exist or is not a directory"); } long maxDocs = Long.MAX_VALUE; if (cmdLine.hasOption(maxOpt)) { maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString()); } if (maxDocs < 0) { throw new IllegalArgumentException("maxDocs must be >= 0"); } String field = cmdLine.getValue(fieldOpt).toString(); PrintWriter out = null; if (cmdLine.hasOption(outputOpt)) { out = new PrintWriter(new FileWriter(cmdLine.getValue(outputOpt).toString())); } else { out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")); } dumpDocumentFields(inputDir, field, maxDocs, out); IOUtils.close(Collections.singleton(out)); } catch (OptionException e) { log.error("Exception", e); CommandLineUtil.printHelp(group); } }
From source file:com.act.lcms.MassCalculator2.java
public static void main(String[] args) throws Exception { CommandLine cl = CLI_UTIL.parseCommandLine(args); if (cl.hasOption(OPTION_LICENSE_FILE)) { LOGGER.info("Using license file at %s", cl.getOptionValue(OPTION_LICENSE_FILE)); LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE)); }/*from w w w . j a va2 s . c o m*/ List<String> inchis = new ArrayList<>(); if (cl.hasOption(OPTION_INPUT_FILE)) { try (BufferedReader reader = new BufferedReader(new FileReader(cl.getOptionValue(OPTION_INPUT_FILE)))) { String line; while ((line = reader.readLine()) != null) { inchis.add(line); } } } if (cl.getArgList().size() > 0) { LOGGER.info("Reading %d InChIs from the command line", cl.getArgList().size()); inchis.addAll(cl.getArgList()); } try (PrintWriter writer = new PrintWriter( cl.hasOption(OPTION_OUTPUT_FILE) ? new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)) : new OutputStreamWriter(System.out))) { writer.format("InChI\tMass\tCharge\n"); for (String inchi : inchis) { try { Pair<Double, Integer> massAndCharge = calculateMassAndCharge(inchi); writer.format("%s\t%.6f\t%3d\n", inchi, massAndCharge.getLeft(), massAndCharge.getRight()); } catch (MolFormatException e) { LOGGER.error("Unable to compute mass for %s: %s", inchi, e.getMessage()); } } } }
From source file:fr.cnrs.sharp.Main.java
public static void main(String args[]) { Options options = new Options(); Option versionOpt = new Option("v", "version", false, "print the version information and exit"); Option helpOpt = new Option("h", "help", false, "print the help"); Option inProvFileOpt = OptionBuilder.withArgName("input_PROV_file_1> ... <input_PROV_file_n") .withLongOpt("input_PROV_files").withDescription("The list of PROV input files, in RDF Turtle.") .hasArgs().create("i"); Option inRawFileOpt = OptionBuilder.withArgName("input_raw_file_1> ... <input_raw_file_n") .withLongOpt("input_raw_files") .withDescription(/*from ww w .java 2 s .co m*/ "The list of raw files to be fingerprinted and possibly interlinked with owl:sameAs.") .hasArgs().create("ri"); Option summaryOpt = OptionBuilder.withArgName("summary").withLongOpt("summary") .withDescription("Materialization of wasInfluencedBy relations.").create("s"); options.addOption(inProvFileOpt); options.addOption(inRawFileOpt); options.addOption(versionOpt); options.addOption(helpOpt); options.addOption(summaryOpt); String header = "SharpTB is a tool to maturate provenance based on PROV inferences"; String footer = "\nPlease report any issue to alban.gaignard@univ-nantes.fr"; try { CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SharpTB", header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { logger.info("SharpTB version 0.1.0"); System.exit(0); } if (cmd.hasOption("ri")) { String[] inFiles = cmd.getOptionValues("ri"); Model model = ModelFactory.createDefaultModel(); for (String inFile : inFiles) { Path p = Paths.get(inFile); if (!p.toFile().isFile()) { logger.error("Cannot find file " + inFile); System.exit(1); } else { //1. fingerprint try { model.add(Interlinking.fingerprint(p)); } catch (IOException e) { logger.error("Cannot fingerprint file " + inFile); } } } //2. genSameAs Model sameAs = Interlinking.generateSameAs(model); sameAs.write(System.out, "TTL"); } if (cmd.hasOption("i")) { String[] inFiles = cmd.getOptionValues("i"); Model data = ModelFactory.createDefaultModel(); for (String inFile : inFiles) { Path p = Paths.get(inFile); if (!p.toFile().isFile()) { logger.error("Cannot find file " + inFile); System.exit(1); } else { RDFDataMgr.read(data, inFile, Lang.TTL); } } Model res = Harmonization.harmonizeProv(data); try { Path pathInfProv = Files.createTempFile("PROV-inf-tgd-egd-", ".ttl"); res.write(new FileWriter(pathInfProv.toFile()), "TTL"); System.out.println("Harmonized PROV written to file " + pathInfProv.toString()); //if the summary option is activated, then save the subgraph and generate a visualization if (cmd.hasOption("s")) { String queryInfluence = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" + "PREFIX prov: <http://www.w3.org/ns/prov#> \n" + "CONSTRUCT { \n" + " ?x ?p ?y .\n" + " ?x rdfs:label ?lx .\n" + " ?y rdfs:label ?ly .\n" + "} WHERE {\n" + " ?x ?p ?y .\n" + " FILTER (?p IN (prov:wasInfluencedBy)) .\n" + " ?x rdfs:label ?lx .\n" + " ?y rdfs:label ?ly .\n" + "}"; Query query = QueryFactory.create(queryInfluence); QueryExecution queryExec = QueryExecutionFactory.create(query, res); Model summary = queryExec.execConstruct(); queryExec.close(); Util.writeHtmlViz(summary); } } catch (IOException ex) { logger.error("Impossible to write the harmonized provenance file."); System.exit(1); } } else { // logger.info("Please fill the -i input parameter."); // HelpFormatter formatter = new HelpFormatter(); // formatter.printHelp("SharpTB", header, options, footer, true); // System.exit(0); } } catch (ParseException ex) { logger.error("Error while parsing command line arguments. Please check the following help:"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SharpToolBox", header, options, footer, true); System.exit(1); } }
From source file:it.cnr.isti.smartfed.papers.qbrokage.BrokageLockin.java
public static void main(String[] args) throws IOException { String initial = "#evo_step,cost,time,used_dc \n"; String str = initial;/* www .j av a 2 s. c o m*/ AbstractAllocator allocator = null; int seed = 1; /* str = initial; allocator = new GreedyAllocator(); str += executeAndWrite(allocator, numDatacenters); str += "\n"; FileWriter fw1 = new FileWriter(new File("plots/lock-greedy-dc"+ dcToString() + ".dat")); fw1.write(str); fw1.flush(); fw1.close(); */ JGAPMapping.MUTATION = 10; JGAPMapping.POP_SIZE = 50; JGAPMapping.CROSSOVER = 0.35; JGAPMapping.EVOLUTION_STEP = 100; allocator = new GeneticAllocator(); str = initial; // warmup with 5 dcs allocator = new GeneticAllocator(); str += executeAndWrite(allocator, numDatacenters); str += "\n"; FileWriter fw2 = new FileWriter( new File("plots/lock-genetic-dc" + dcToString() + "cross0.35-mut10" + ".dat")); fw2.write(str); fw2.flush(); fw2.close(); }
From source file:com.github.fritaly.graphml4j.samples.GradleDependenciesWithGroupsAndBuffering.java
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println(String.format("%s <output-file>", GradleDependenciesWithGroupsAndBuffering.class.getSimpleName())); System.exit(1);/*from www . ja v a2 s .co m*/ } final File file = new File(args[0]); System.out.println("Writing GraphML file to " + file.getAbsolutePath() + " ..."); FileWriter fileWriter = null; Reader reader = null; LineNumberReader lineReader = null; try { fileWriter = new FileWriter(file); final com.github.fritaly.graphml4j.datastructure.Graph graph = new Graph(); // The dependency graph has been generated by Gradle with the // command "gradle dependencies". The output of this command has // been saved to a text file which will be parsed to rebuild the // dependency graph reader = new InputStreamReader( GradleDependenciesWithGroupsAndBuffering.class.getResourceAsStream("gradle-dependencies.txt")); lineReader = new LineNumberReader(reader); String line = null; // Stack containing the nodes per depth inside the dependency graph // (the topmost dependency is the first one in the stack) final Stack<Node> parentNodes = new Stack<Node>(); while ((line = lineReader.readLine()) != null) { // Determine the depth of the current dependency inside the // graph. The depth can be inferred from the indentation used by // Gradle. Each level of depth adds 5 more characters of // indentation final int initialLength = line.length(); // Remove the strings used by Gradle to indent dependencies line = StringUtils.replace(line, "+--- ", ""); line = StringUtils.replace(line, "| ", ""); line = StringUtils.replace(line, "\\--- ", ""); line = StringUtils.replace(line, " ", ""); // The depth can easily be inferred now final int depth = (initialLength - line.length()) / 5; // Remove unnecessary node ids while (depth <= parentNodes.size()) { parentNodes.pop(); } final Artifact artifact = createArtifact(line); Node node = graph.getNodeByData(artifact); // Has this dependency already been added to the graph ? if (node == null) { // No, add the node node = graph.addNode(artifact); } parentNodes.push(node); if (parentNodes.size() > 1) { // Generate an edge between the current node and its parent graph.addEdge("Depends on", parentNodes.get(parentNodes.size() - 2), node); } } // Create the groups after creating the nodes & edges for (Node node : graph.getNodes()) { final Artifact artifact = (Artifact) node.getData(); final String groupId = artifact.group; Node groupNode = graph.getNodeByData(groupId); if (groupNode == null) { groupNode = graph.addNode(groupId); } // add the node to the group node.setParent(groupNode); } graph.toGraphML(fileWriter, new Renderer() { @Override public String getNodeLabel(Node node) { return node.isGroup() ? node.getData().toString() : ((Artifact) node.getData()).getLabel(); } @Override public boolean isGroupOpen(Node node) { return true; } @Override public NodeStyle getNodeStyle(Node node) { // Customize the rendering of nodes final NodeStyle nodeStyle = new NodeStyle(); nodeStyle.setWidth(250.0f); return nodeStyle; } @Override public GroupStyles getGroupStyles(Node node) { return new GroupStyles(); } @Override public EdgeStyle getEdgeStyle(Edge edge) { return new EdgeStyle(); } }); System.out.println("Done"); } finally { // Calling GraphMLWriter.close() is necessary to dispose the underlying resources fileWriter.close(); lineReader.close(); reader.close(); } }