List of usage examples for java.io FileWriter FileWriter
public FileWriter(FileDescriptor fd)
From source file:eu.smartfp7.terrier.sensor.CouchDBTimeCrowdPlotter.java
public static void main(String[] args) throws IOException { Database db = new Database("dusk.ait.gr/couchdb", 80, "smart_test_crowd"); DesignDocument designDocument = db.getDesignDocument("getTimeNdensity"); View view = designDocument.getView("timeNdensity"); ViewResult<Object> vr = db.query("_design/getTimeNdensity/_view/timeNdensity", Object.class, new Options(), new JSONParser(), null); FileWriter fileWriter = new FileWriter(new File(args[0])); for (ValueRow<Object> v : vr.getRows()) { System.out.println(v.getKey() + "," + v.getValue()); fileWriter.append(v.getKey() + "," + v.getValue() + "\n"); }/*from www .j a va 2s. c o m*/ }
From source file:PDFDemo.java
public static void main(String[] argv) throws IOException { PrintWriter pout;//from w ww.j a v a2s . c om if (argv.length == 0) { pout = new PrintWriter(System.out); } else { if (new File(argv[0]).exists()) { throw new IOException("Output file " + argv[0] + " already exists"); } pout = new PrintWriter(new FileWriter(argv[0])); } PDF p = new PDF(pout); Page p1 = new Page(p); p1.add(new MoveTo(p, 100, 600)); p1.add(new Text(p, "Hello world, live on the web.")); p1.add(new Text(p, "Hello world, line 2 on the web.")); p.add(p1); p.setAuthor("Ian F. Darwin"); p.writePDF(); }
From source file:GetDirectDownload.java
/** * @param args// w w w .j a v a 2 s . c o m * @throws ParseException */ public static void main(final String[] args) throws ParseException { // you can either set the 2 strings above, or pass them in to this program if (args.length == 2) { USER_NAME = args[0]; API_KEY = args[1]; } // make sure the credentials got set if (USER_NAME.equals("<YOUR USER NAME>") || API_KEY.equals("<YOUR API KEY>")) { System.err.println( "You must either edit this example file and put in your username and apikey OR pass them in as program arguments"); System.exit(1); } final ApiCredentials credentials = new ApiCredentials(USER_NAME, API_KEY); final NZBMatrixApi api = new NZBMatrixApi(credentials); try { // makes the request to the nzbMatrixAPI for a direct download of a particular post id final DirectDownloadResponse directDownload = api.getDirectDownload(314694); // save the nzb file to disk final String fileName = directDownload.getSuggestedFileName(); final BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); out.write(directDownload.getNzbFileContents()); out.close(); System.out.println("Nzb File Saved As: " + fileName); } catch (final ClientProtocolException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } catch (final NZBMatrixApiException e) { e.printStackTrace(); } }
From source file:model.experiments.tuningRuns.CompetitiveAveragingGridSearch.java
public static void main(String[] args) throws IOException { FileWriter writer;/* = new FileWriter(Paths.get("runs", "tunings","averaging", "averagingTuning.csv").toFile()); // w w w . j ava 2s .com for(float hrWeight= .1f; hrWeight<1f;hrWeight= round(hrWeight+.1f,1)) for(float salesWeight= .1f; salesWeight<1f;salesWeight= round(salesWeight+.1f,1)) for(PriceAverager.NoTradingDayPolicy hrPolicy : PriceAverager.NoTradingDayPolicy.values()) for(PriceAverager.NoTradingDayPolicy salesPolicy : PriceAverager.NoTradingDayPolicy.values()) { final CompetitiveAveragingResult r = exponentialRuns(hrWeight, hrPolicy, salesWeight, salesPolicy,20); final String line = hrWeight + "," + hrPolicy + "," + salesWeight + "," + salesPolicy + "," + r.getPrice() + "," + r.getQuantity() + "," + r.getStd(); System.out.println(line); writer.write(line+"\n"); } */ writer = new FileWriter(Paths.get("runs", "tunings", "averaging", "intervalTuning.csv").toFile()); for (float hrWeight = .1f; hrWeight < 1f; hrWeight = round(hrWeight + .1f, 1)) for (float salesWeight = .1f; salesWeight < 1f; salesWeight = round(salesWeight + .1f, 1)) { final CompetitiveAveragingResult r = intervalRuns(hrWeight, salesWeight); final String line = hrWeight + "," + salesWeight + "," + r.getPrice() + "," + r.getQuantity() + "," + r.getStd(); System.out.println(line); writer.write(line + "\n"); writer.flush(); } writer.close(); writer = new FileWriter(Paths.get("runs", "tunings", "averaging", "weightedAveragingTuning.csv").toFile()); for (int hrDays = 1; hrDays <= 10; hrDays++) for (int salesDays = 1; salesDays <= 10; salesDays++) for (boolean hrDecorated : new boolean[] { false, true }) for (boolean salesDecorated : new boolean[] { false, true }) { final CompetitiveAveragingResult r = weightedRun(hrDays, salesDays, hrDecorated, salesDecorated); final String line = hrDays + "," + salesDays + "," + hrDecorated + "," + salesDecorated + "," + r.getPrice() + "," + r.getQuantity() + "," + r.getStd(); System.out.println(line); writer.write(line + "\n"); writer.flush(); } writer = new FileWriter(Paths.get("runs", "tunings", "averaging", "doesSpeedMatters.csv").toFile()); /* for(int speed=1; speed<100; speed++) { final CompetitiveAveragingResult r = exponentialRuns(.8f, PriceAverager.NoTradingDayPolicy.COUNT_AS_LAST_CLOSING_PRICE, .8f, PriceAverager.NoTradingDayPolicy.COUNT_AS_LAST_CLOSING_PRICE, speed); final String line = speed + "," + r.getPrice() + "," + r.getQuantity() + "," + r.getStd(); System.out.println(line); writer.write(line+"\n"); } */ }
From source file:GetAppInfo.java
/** * @param args/* ww w .j a va 2s.c om*/ */ public static void main(String[] args) { if (args.length != 4) { System.out.println("Usage :\n" + "java -jar this_jar_name confpath query_str startIndex numbers"); System.exit(1); } String confpath = args[0]; GetAppConfig conf = new GetAppConfig(confpath); String email = conf.getUserID(); String password = conf.getPassword(); String query = args[1]; final int startIndex = Integer.parseInt(args[2]); final int numbers = Integer.parseInt(args[3]); String androidid = conf.getDeviceID(); if (email.equals("")) { System.out.println("Error: Failed to get UserID."); System.exit(2); } else if (password.equals("")) { System.out.println("Error: Failed to get Password."); System.exit(3); } else if (androidid.equals("")) { System.out.println("Error: Failed to get DeviceID."); System.exit(4); } System.out.println("query: " + query); MarketSession session = new MarketSession(); session.getContext().setAndroidId(androidid); Locale locale = new Locale("ja", "JP"); session.setLocale(locale); session.setOperator("NTT DOCOMO", "44010"); session.getContext().setDeviceAndSdkVersion("passion:8"); try { session.login(email, password, androidid); } catch (Exception e) { System.out.println("Error: failed to login.: " + e.getMessage()); System.exit(1); } AppsRequest appsRequest = AppsRequest.newBuilder().setQuery(query).setStartIndex(startIndex) .setEntriesCount(numbers).setWithExtendedInfo(true).build(); Callback<AppsResponse> callback = new Callback<AppsResponse>() { @Override public void onResult(ResponseContext context, AppsResponse response) { int totalcnt, cnt; JsonFactory factory = new JsonFactory(); try { JsonGenerator generator = factory.createGenerator(new FileWriter(new File("pkginfo.json"))); generator.writeStartObject(); //generator.setRootValueSeparator(new SerializedString("\n")); if (response != null) { totalcnt = response.getEntriesCount(); cnt = response.getAppCount(); System.out.println("startIndex = " + startIndex); System.out.println("entriesCount = " + numbers); System.out.println("totalcount = " + totalcnt); System.out.println("count = " + cnt); generator.writeNumberField("startIndex", startIndex); generator.writeNumberField("entriesCount", numbers); generator.writeNumberField("total", totalcnt); generator.writeNumberField("count", cnt); generator.writeRaw("\n"); } else { cnt = -1; } generator.writeFieldName("dataset"); generator.writeStartArray(); if (cnt > 0) { for (int i = 0; ((i < cnt) && (i < numbers)); i++) { generator.writeStartObject(); generator.writeNumberField("num", i + startIndex); System.out.println( "------------------------------------------------------------------------------------"); int counter = i + startIndex; System.out.println(counter + ":"); System.out.println( "------------------------------------------------------------------------------------"); generator.writeStringField("title", response.getApp(i).getTitle()); generator.writeStringField("appType", "" + response.getApp(i).getAppType()); generator.writeStringField("category", response.getApp(i).getExtendedInfo().getCategory()); generator.writeStringField("rating", response.getApp(i).getRating()); generator.writeNumberField("ratingCount", response.getApp(i).getRatingsCount()); generator.writeStringField("countText", response.getApp(i).getExtendedInfo().getDownloadsCountText()); generator.writeStringField("creatorId", response.getApp(i).getCreatorId()); generator.writeStringField("id", response.getApp(i).getId()); generator.writeStringField("packageName", response.getApp(i).getPackageName()); generator.writeStringField("version", response.getApp(i).getVersion()); generator.writeNumberField("versionCode", response.getApp(i).getVersionCode()); generator.writeStringField("price", response.getApp(i).getPrice()); generator.writeNumberField("priceMicros", response.getApp(i).getPriceMicros()); generator.writeStringField("priceCurrency", response.getApp(i).getPriceCurrency()); generator.writeStringField("contactWebsite", response.getApp(i).getExtendedInfo().getContactWebsite()); generator.writeNumberField("screenshotsCount", response.getApp(i).getExtendedInfo().getScreenshotsCount()); generator.writeNumberField("installSize", response.getApp(i).getExtendedInfo().getInstallSize()); generator.writeStringField("permissionIdList", "" + response.getApp(i).getExtendedInfo().getPermissionIdList()); generator.writeStringField("promotoText", response.getApp(i).getExtendedInfo().getPromoText()); generator.writeStringField("description", response.getApp(i).getExtendedInfo().getDescription()); System.out.println("title: " + response.getApp(i).getTitle()); System.out.println("appType: " + response.getApp(i).getAppType()); System.out.println("category: " + response.getApp(i).getExtendedInfo().getCategory()); System.out.println("rating: " + response.getApp(i).getRating()); System.out.println("ratingsCount: " + response.getApp(i).getRatingsCount()); System.out .println("count: " + response.getApp(i).getExtendedInfo().getDownloadsCount()); System.out.println( "countText: " + response.getApp(i).getExtendedInfo().getDownloadsCountText()); System.out.println("creator: " + response.getApp(i).getCreator()); System.out.println("creatorId: " + response.getApp(i).getCreatorId()); System.out.println("id: " + response.getApp(i).getId()); System.out.println("packageName: " + response.getApp(i).getPackageName()); System.out.println("version: " + response.getApp(i).getVersion()); //System.out.println("contactEmail: " + response.getApp(i).getExtendedInfo().getContactEmail()); //System.out.println("contactPhone: " + response.getApp(i).getExtendedInfo().getContactPhone()); System.out.println( "installSize: " + response.getApp(i).getExtendedInfo().getInstallSize()); generator.writeEndObject(); generator.writeRaw("\n"); } } else if (cnt == 0) { System.out.println("no hit"); } else { System.out.println("Bad Reqeust"); } generator.writeEndArray(); generator.writeEndObject(); generator.close(); } catch (Exception e) { System.out.println("Error: pkginfo(): " + e.getMessage()); } } // onResult() }; session.append(appsRequest, callback); session.flush(); }
From source file:TwitterClustering.java
public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here File outFile = new File(args[3]); Scanner s = new Scanner(new File(args[1])).useDelimiter(","); JSONParser parser = new JSONParser(); Set<Cluster> clusterSet = new HashSet<Cluster>(); HashMap<String, Tweet> tweets = new HashMap(); FileWriter fw = new FileWriter(outFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); // init//from w w w. j av a 2s .com try { Object obj = parser.parse(new FileReader(args[2])); JSONArray jsonArray = (JSONArray) obj; for (int i = 0; i < jsonArray.size(); i++) { Tweet twt = new Tweet(); JSONObject jObj = (JSONObject) jsonArray.get(i); String text = jObj.get("text").toString(); long sum = 0; for (int y = 0; y < text.toCharArray().length; y++) { sum += (int) text.toCharArray()[y]; } String[] token = text.split(" "); String tID = jObj.get("id").toString(); Set<String> mySet = new HashSet<String>(Arrays.asList(token)); twt.setAttributeValue(sum); twt.setText(mySet); twt.setTweetID(tID); tweets.put(tID, twt); } // preparing initial clusters int i = 0; while (s.hasNext()) { String id = s.next();// id Tweet t = tweets.get(id.trim()); clusterSet.add(new Cluster(i + 1, t, new LinkedList())); i++; } Iterator it = tweets.entrySet().iterator(); for (int l = 0; l < 2; l++) { // limit to 25 iterations while (it.hasNext()) { Map.Entry me = (Map.Entry) it.next(); // calculate distance to each centroid Tweet p = (Tweet) me.getValue(); HashMap<Cluster, Float> distMap = new HashMap(); for (Cluster clust : clusterSet) { distMap.put(clust, jaccardDistance(p.getText(), clust.getCentroid().getText())); } HashMap<Cluster, Float> sorted = (HashMap<Cluster, Float>) sortByValue(distMap); sorted.keySet().iterator().next().getMembers().add(p); } // calculate new centroid and update Clusterset for (Cluster clust : clusterSet) { TreeMap<String, Long> tDistMap = new TreeMap(); Tweet newCentroid = null; Long avgSumDist = new Long(0); for (int j = 0; j < clust.getMembers().size(); j++) { avgSumDist += clust.getMembers().get(j).getAttributeValue(); tDistMap.put(clust.getMembers().get(j).getTweetID(), clust.getMembers().get(j).getAttributeValue()); } if (clust.getMembers().size() != 0) { avgSumDist /= (clust.getMembers().size()); } ArrayList<Long> listValues = new ArrayList<Long>(tDistMap.values()); if (tDistMap.containsValue(findClosestNumber(listValues, avgSumDist))) { // found closest newCentroid = tweets .get(getKeyByValue(tDistMap, findClosestNumber(listValues, avgSumDist))); clust.setCentroid(newCentroid); } } } // create an iterator Iterator iterator = clusterSet.iterator(); // check values while (iterator.hasNext()) { Cluster c = (Cluster) iterator.next(); bw.write(c.getId() + "\t"); System.out.print(c.getId() + "\t"); for (Tweet t : c.getMembers()) { bw.write(t.getTweetID() + ", "); System.out.print(t.getTweetID() + ","); } bw.write("\n"); System.out.println(""); } System.out.println(""); System.out.println("SSE " + sumSquaredErrror(clusterSet)); } catch (Exception e) { e.printStackTrace(); } finally { bw.close(); fw.close(); } }
From source file:metaTile.Main.java
/** * @param args//from ww w . ja v a 2s.co m * @throws IOException */ public static void main(String[] args) throws IOException { try { /* parse the command line arguments */ // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption("i", "input", true, "File to read original tile list from."); options.addOption("o", "output", true, "File to write shorter meta-tile list to."); options.addOption("m", "metatiles", true, "Number of tiles in x and y direction to group into one meta-tile."); // parse the command line arguments CommandLine commandLine = parser.parse(options, args); if (!commandLine.hasOption("input") || !commandLine.hasOption("output") || !commandLine.hasOption("metatiles")) printUsage(options); String inputFileName = commandLine.getOptionValue("input"); String outputFileName = commandLine.getOptionValue("output"); int metaTileSize = Integer.parseInt(commandLine.getOptionValue("metatiles")); ArrayList<RenderingTile> tiles = new ArrayList<RenderingTile>(); BufferedReader tileListReader = new BufferedReader(new FileReader(new File(inputFileName))); BufferedWriter renderMetatileListWriter = new BufferedWriter(new FileWriter(new File(outputFileName))); String line = tileListReader.readLine(); while (line != null) { String[] columns = line.split("/"); if (columns.length == 3) tiles.add(new RenderingTile(Integer.parseInt(columns[0]), Integer.parseInt(columns[1]), Integer.parseInt(columns[2]))); line = tileListReader.readLine(); } tileListReader.close(); int hits = 0; // tiles which we are already rendering as the top left corner of 4x4 metatiles HashSet<RenderingTile> whitelist = new HashSet<RenderingTile>(); // for each tile in the list see if it has a meta-tile in the whitelist already for (int i = 0; i < tiles.size(); i++) { boolean hit = false; // by default we aren't already rendering this tile as part of another metatile for (int dx = 0; dx < metaTileSize; dx++) { for (int dy = 0; dy < metaTileSize; dy++) { RenderingTile candidate = new RenderingTile(tiles.get(i).z, tiles.get(i).x - dx, tiles.get(i).y - dy); if (whitelist.contains(candidate)) { hit = true; // now exit the two for loops iterating over tiles inside a meta-tile dx = metaTileSize; dy = metaTileSize; } } } // if this tile doesn't already have a meta-tile in the whitelist, add it if (hit == false) { hits++; renderMetatileListWriter.write(tiles.get(i).toString() + "/" + metaTileSize + "\n"); whitelist.add(tiles.get(i)); } } renderMetatileListWriter.close(); System.out.println( "Reduced " + tiles.size() + " tiles into " + hits + " metatiles of size " + metaTileSize); } catch (Exception e) { e.printStackTrace(); } }
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 ww w . ja v a 2 s . c o 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.ontopia.persistence.rdbms.DDLWriter.java
public static void main(String[] argv) throws Exception { // Initialize logging CmdlineUtils.initializeLogging();//from w w w .j a va2s . com // Initialize command line option parser and listeners CmdlineOptions options = new CmdlineOptions("DDLWriter", argv); // Register logging options CmdlineUtils.registerLoggingOptions(options); // Parse command line options try { options.parse(); } catch (CmdlineOptions.OptionsException e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } // Get command line arguments String[] args = options.getArguments(); if (args.length < 3) { System.err.println("Error: need exactly two files as arguments."); usage(); System.exit(1); } String schema = args[0]; String dbtype = args[1]; String[] platforms = StringUtils.split(args[2], ","); String createfile = args[3]; String dropfile = args[4]; Project project = DatabaseProjectReader.loadProject(schema); GenericSQLProducer producer; switch (dbtype) { case "postgresql": producer = new PostgreSQLProducer(project, platforms); break; case "oracle": producer = new OracleSQLProducer(project, platforms); break; case "sqlserver": producer = new SQLServerSQLProducer(project, platforms); break; case "mysql": producer = new MySqlSQLProducer(project, platforms); break; case "db2": producer = new DB2SQLProducer(project, platforms); break; case "firebird": producer = new FirebirdSQLProducer(project, platforms); break; default: producer = new GenericSQLProducer(project, platforms); break; } // Generate create file Writer cwriter = new FileWriter(createfile); producer.writeCreate(cwriter); cwriter.close(); // Generate create file Writer dwriter = new FileWriter(dropfile); producer.writeDrop(dwriter); dwriter.close(); }
From source file:de.mpg.escidoc.services.edoc.CreatePurgeScript2.java
/** * @param args//from ww w . j ava2s . c o m */ public static void main(String[] args) throws Exception { CORESERVICES_URL = PropertyReader.getProperty("escidoc.framework_access.framework.url"); String userHandle = AdminHelper.loginUser(args[0], args[1]); logger.info("Querying core-services..."); HttpClient httpClient = new HttpClient(); String filter = "<param><filter name=\"http://escidoc.de/core/01/structural-relations/context\">" + IMPORT_CONTEXT + "</filter><filter name=\"/properties/public-status\">released</filter><order-by>http://escidoc.de/core/01/properties/creation-date</order-by><limit>0</limit></param>"; PostMethod postMethod = new PostMethod(CORESERVICES_URL + "/ir/items/filter"); postMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle); postMethod.setRequestBody(filter); ProxyHelper.executeMethod(httpClient, postMethod); String response = postMethod.getResponseBodyAsString(); logger.info("...done!"); FileWriter xmlData = new FileWriter("xmlData.xml"); xmlData.write(response); xmlData.close(); //System.out.println(response); logger.info("Transforming result..."); XSLTTransform transform = new XSLTTransform(); File stylesheet = new File("src/main/resources/itemlist2purgescript.xslt"); FileOutputStream outputStream = new FileOutputStream("purge.sh"); transform.transform(response, stylesheet, outputStream); logger.info("...done!"); logger.info("Finished!"); }