List of usage examples for java.io BufferedWriter append
public Writer append(CharSequence csq) throws IOException
From source file:Main.java
public static void main(String[] args) throws IOException { StringWriter sw = new StringWriter(); BufferedWriter bw = new BufferedWriter(sw); bw.append("java2s.com"); bw.close();//from www .ja v a 2 s . co m System.out.println(sw.getBuffer()); // appending after closing will throw error bw.append("2"); System.out.println(sw.getBuffer()); }
From source file:Main.java
public static void main(String[] args) throws IOException { String letters = "from java2s.com"; StringWriter sw = new StringWriter(); BufferedWriter bw = new BufferedWriter(sw); for (char c : letters.toCharArray()) { bw.append(c); bw.flush();// w w w . j a v a2s. co m System.out.println(sw.getBuffer()); } }
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 ww. ja va2 s .co 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:ASCII2NATIVE.java
public static void main(String[] args) { File f = new File("c:\\mydb.script"); File f2 = new File("c:\\mydb3.script"); if (f.exists() && f.isFile()) { // convert param-file BufferedReader br = null; StringBuffer sb = new StringBuffer(); String line;/*ww w . j a va 2 s .c o m*/ try { br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "JISAutoDetect")); while ((line = br.readLine()) != null) { System.out.println(ascii2Native(line)); sb.append(ascii2Native(line)).append(";\n");//.append(";\n\r") } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f2), "utf-8")); out.append(sb.toString()); out.flush(); out.close(); } catch (FileNotFoundException e) { System.err.println("file not found - " + f); } catch (IOException e) { System.err.println("read error - " + f); } finally { try { if (br != null) br.close(); } catch (Exception e) { } } } else { // // convert param-data // System.out.print(ascii2native(args[i])); // if (i + 1 < args.length) // System.out.print(' '); } }
From source file:eu.fbk.dkm.sectionextractor.PageClassMerger.java
public static void main(String args[]) throws IOException { CommandLineWithLogger commandLineWithLogger = new CommandLineWithLogger(); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("WikiData ID file").isRequired().withLongOpt("wikidata-id").create("i")); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("Airpedia Person file").isRequired().withLongOpt("airpedia").create("a")); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Output file") .isRequired().withLongOpt("output").create("o")); CommandLine commandLine = null;/* ww w. j a va 2 s. c o m*/ try { commandLine = commandLineWithLogger.getCommandLine(args); PropertyConfigurator.configure(commandLineWithLogger.getLoggerProps()); } catch (Exception e) { System.exit(1); } String wikiIDFileName = commandLine.getOptionValue("wikidata-id"); String airpediaFileName = commandLine.getOptionValue("airpedia"); String outputFileName = commandLine.getOptionValue("output"); HashMap<Integer, String> wikiIDs = new HashMap<>(); HashSet<Integer> airpediaClasses = new HashSet<>(); List<String> strings; logger.info("Loading file " + wikiIDFileName); strings = Files.readLines(new File(wikiIDFileName), Charsets.UTF_8); for (String line : strings) { line = line.trim(); if (line.length() == 0) { continue; } if (line.startsWith("#")) { continue; } String[] parts = line.split("\t"); if (parts.length < 2) { continue; } int id; try { id = Integer.parseInt(parts[0]); } catch (Exception e) { continue; } wikiIDs.put(id, parts[1]); } logger.info("Loading file " + airpediaFileName); strings = Files.readLines(new File(airpediaFileName), Charsets.UTF_8); for (String line : strings) { line = line.trim(); if (line.length() == 0) { continue; } if (line.startsWith("#")) { continue; } String[] parts = line.split("\t"); if (parts.length < 2) { continue; } int id; try { id = Integer.parseInt(parts[0]); } catch (Exception e) { continue; } airpediaClasses.add(id); } logger.info("Saving information"); BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName)); for (int i : wikiIDs.keySet()) { if (!airpediaClasses.contains(i)) { continue; } writer.append(wikiIDs.get(i)).append("\n"); } writer.close(); }
From source file:fr.eo.util.dumper.Dumper.java
/** * @param args/* ww w .j a v a2 s. co m*/ */ public static void main(String[] args) { String appName = args[0]; System.out.println("Starting dumper ..."); Statement stmt = null; try { System.out.println("Getting database connection ..."); Connection conn = getJtdsConnection(); List<RequestDefinitionBean> requests = RequestDefinitionParser.getRequests(appName); assetFolder = RequestDefinitionParser.getAppBaseDir(appName) + "assets/"; for (RequestDefinitionBean request : requests) { int currentFileSize = 0, cpt = 1; stmt = conn.createStatement(); System.out.println("Dumping " + request.name + "..."); ResultSet rs = stmt.executeQuery(request.sql); BufferedWriter bw = getWriter(request.name, cpt); bw.append(COPYRIGHTS); currentFileSize += COPYRIGHTS.length(); bw.append("--" + request.name + "\n"); while (rs.next()) { StringBuilder sb = new StringBuilder(); sb.append("INSERT INTO "); sb.append(request.table).append(" VALUES ("); int pos = 0; for (String fieldName : request.fields) { String str = getFieldValue(request, pos, rs, fieldName); sb.append(str); pos++; if (pos < request.fields.size()) { sb.append(","); } } sb.append(");\n"); currentFileSize += sb.length(); bw.append(sb.toString()); bw.flush(); if (currentFileSize > MAX_FILE_SIZE) { bw.close(); bw = getWriter(request.name, ++cpt); bw.append(COPYRIGHTS); bw.append("--" + request.name + "\n"); currentFileSize = COPYRIGHTS.length(); } } bw.flush(); bw.close(); } System.out.println("done."); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } DumpFilesDescriptor descriptor = new DumpFilesDescriptor(); descriptor.lineNumbers = getDumpLinesNumber(); descriptor.dumpFileNames = dumpFileNames; writeDescriptorFile(descriptor); System.out.println("nb :" + descriptor.lineNumbers); }
From source file:org.lieuofs.extraction.commune.historisation.ExtractionNumHistorisationCommune.java
/** * @param args/*from ww w . j av a2 s. c o m*/ */ public static void main(String[] args) throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "beans_lieuofs.xml" }); CommuneCritere critere = new CommuneCritere(); IGestionCommune gestionnaire = (IGestionCommune) context.getBean("gestionCommune"); List<ICommuneSuisse> communes = gestionnaire.rechercher(critere); Collections.sort(communes, new Comparator<ICommuneSuisse>() { public int compare(ICommuneSuisse com1, ICommuneSuisse com2) { return com1.getNumeroOFS() - com2.getNumeroOFS(); } }); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("NumeroHistorisationCommune.sql"), "Windows-1252")); NumeroHistorisationCommuneWriter commWriter = new NumeroHistorisationRefonteSQLWriter(); for (ICommuneSuisse commune : communes) { String numHistStr = commWriter.ecrireNumero(commune); if (null != numHistStr) { writer.append(numHistStr); } } writer.close(); }
From source file:org.apache.mahout.utils.vectors.libsvm.Driver.java
/** * The main method./*ww w . ja v a 2 s .c o m*/ * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option inputOpt = obuilder.withLongName("input").withRequired(true) .withArgument(abuilder.withName("input").withMinimum(1).withMaximum(1).create()) .withDescription( "The file or directory containing the ARFF files. If it is a directory, all .arff files will be converted") .withShortName("d").create(); Option outputOpt = obuilder.withLongName("output").withRequired(true) .withArgument(abuilder.withName("output").withMinimum(1).withMaximum(1).create()) .withDescription( "The output directory. Files will have the same name as the input, but with the extension .mvc") .withShortName("o").create(); Option maxOpt = obuilder.withLongName("max").withRequired(false) .withArgument(abuilder.withName("max").withMinimum(1).withMaximum(1).create()) .withDescription( "The maximum number of vectors to output. If not specified, then it will loop over all docs") .withShortName("m").create(); Option dictOutOpt = obuilder.withLongName("dictOut").withRequired(true) .withArgument(abuilder.withName("dictOut").withMinimum(1).withMaximum(1).create()) .withDescription("The file to output the label bindings").withShortName("t").create(); Option outWriterOpt = obuilder.withLongName("outputWriter").withRequired(false) .withArgument(abuilder.withName("outputWriter").withMinimum(1).withMaximum(1).create()) .withDescription( "The VectorWriter to use, either seq (SequenceFileVectorWriter - default) or file (Writes to a File using JSON format)") .withShortName("e").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(helpOpt).withOption(dictOutOpt).withOption(outWriterOpt).create(); try { Parser parser = new Parser(); parser.setGroup(group); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } if (cmdLine.hasOption(inputOpt)) {// Lucene case File input = new File(cmdLine.getValue(inputOpt).toString()); 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 outDir = cmdLine.getValue(outputOpt).toString(); Driver.log.info("Output Dir: {}", outDir); String outWriter = null; if (cmdLine.hasOption(outWriterOpt)) { outWriter = cmdLine.getValue(outWriterOpt).toString(); } File dictOut = new File(cmdLine.getValue(dictOutOpt).toString()); List<Double> labels = new ArrayList<Double>(); if (input.exists() && input.isDirectory()) { File[] files = input.listFiles(); for (File file : files) { // Driver.writeFile(outWriter, outDir, file, maxDocs, labels); } } else { // Driver.writeFile(outWriter, outDir, input, maxDocs, labels); } Driver.log.info("Dictionary Output file: {}", dictOut); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(dictOut), Charset.forName("UTF8"))); for (Double label : labels) { writer.append(label.toString()).append('\n'); } writer.close(); } } catch (OptionException e) { Driver.log.error("Exception", e); CommandLineUtil.printHelp(group); } }
From source file:recsyslod.utils.DownloadLodProperties.java
/** * @param args the command line arguments *///from w w w . j av a 2 s . c o m public static void main(String[] args) { if (args.length == 2) { try { int c = 0; System.out.println(); BufferedWriter writer = new BufferedWriter(new FileWriter(args[1])); BufferedReader reader = new BufferedReader(new FileReader(args[0])); while (reader.ready()) { String[] split = reader.readLine().split("\t"); String id = split[0]; String uri = split[2]; List<Pair<String, String>> properties = getProperties(uri); for (Pair<String, String> p : properties) { writer.append(id).append("\t").append(p.getLeft()).append("\t").append(p.getRight()); writer.newLine(); } c++; if (c % 10 == 0) { System.out.print("."); if (c % 1000 == 0) { System.out.println("." + c); } } } reader.close(); writer.close(); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } } }
From source file:com.cyberway.issue.net.PublicSuffixes.java
/** * Utility method for dumping a regex String, based on a published public * suffix list, which matches any SURT-form hostname up through the broadest * 'private' (assigned/sold) domain-segment. That is, for any of the * SURT-form hostnames...//from ww w . j av a 2 s. c om * * com,example, com,example,www, com,example,california,www * * ...the regex will match 'com,example,'. * * @param args * @throws IOException */ public static void main(String args[]) throws IOException { String regex; if (args.length == 0 || "=".equals(args[0])) { // use bundled list regex = getTopmostAssignedSurtPrefixRegex(); } else { // use specified filename BufferedReader reader = new BufferedReader(new FileReader(args[0])); regex = getTopmostAssignedSurtPrefixRegex(reader); IOUtils.closeQuietly(reader); } boolean needsClose = false; BufferedWriter writer; if (args.length >= 2) { // writer to specified file writer = new BufferedWriter(new FileWriter(args[1])); needsClose = true; } else { // write to stdout writer = new BufferedWriter(new OutputStreamWriter(System.out)); } writer.append(regex); writer.flush(); if (needsClose) { writer.close(); } }