List of usage examples for java.io FileWriter write
public void write(int c) throws IOException
From source file:bigtweet.model.StudyingBeacons.java
/** * Extra ouput file to generate a chart * call plotBeaconStudy in R project to obtain chart */// w w w . j av a 2s . co m private void generateBatchOuputForChart(JSONArray parametersValues, int parametersValuesIndex, double meanEndorsers) { JSONObject parameters = (JSONObject) parametersValues.get(parametersValuesIndex);//parameters JSONObject aux = new JSONObject(); aux.put("links", parameters.get("beaconLinksNumber")); aux.put("centrality", parameters.get("beaconLinksCentrality")); DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US); DecimalFormat df = new DecimalFormat("0.000", otherSymbols); aux.put("meanEndorsers", df.format(meanEndorsers)); JSONForChart.add(aux); //write json file FileWriter file; try { file = new FileWriter(batchOutputFileForChart); file.write(JSONForChart.toJSONString()); file.flush(); file.close(); } catch (Exception ex) { Logger.getLogger(BTSimBatch.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.granita.contacticloudsync.ui.DebugInfoActivity.java
public void onShare(MenuItem item) { if (!TextUtils.isEmpty(report)) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.setType("text/plain"); sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Exception Details"); try {//from www .java 2 s .c om File reportFile = File.createTempFile("debug", ".txt", getExternalCacheDir()); Constants.log.debug("Writing debug info to " + reportFile.getAbsolutePath()); FileWriter writer = new FileWriter(reportFile); writer.write(report); writer.close(); sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(reportFile)); } catch (IOException e) { // let's hope the report is < 1 MB sendIntent.putExtra(Intent.EXTRA_TEXT, report); } startActivity(sendIntent); } }
From source file:com.amazonaws.mturk.cmd.CreateQualificationType.java
public boolean createQualificationType(String qualFile, String answerFile, String propertiesFile, boolean noRetry) { String test = null;//from w ww . ja v a 2 s. c om String answerKey = null; Properties props = new Properties(); try { if (qualFile != null) { test = new FileUtil(qualFile).getString(); } props = super.loadProperties(propertiesFile); if (answerFile != null) { answerKey = (new FileUtil(answerFile)).getString(); } } catch (FileNotFoundException e) { log.error("Couldn't find one of the necessary files: " + e.getLocalizedMessage(), e); return false; } catch (IOException e) { log.error("Error reading one of the necessary files: " + e.getLocalizedMessage(), e); return false; } String autoGranted = props.getProperty("autogranted"); String autoGrantedValue = props.getProperty("autograntedvalue"); String testDuration = props.getProperty("testdurationinseconds", "10800"); //default to 3 hours Long retryDelay = noRetry ? null : Long.valueOf(props.getProperty("retrydelayinseconds", "259200")); // default to 3 days String qualName = props.getProperty("name"); if (qualName == null || qualName.trim().length() == 0) { log.error( "Cannot create qualification type. The qualification name is not set. Please enter a value in the 'name' field in the properties file (" + propertiesFile + ")"); return false; } try { // merge Velocity templates if any test = getMergedTemplate(qualFile); answerKey = getMergedTemplate(answerFile); QualificationType qualType = service.createQualificationType(qualName, props.getProperty("keywords"), props.getProperty("description"), QualificationTypeStatus.Active, retryDelay, // retryDelayInSeconds test, answerKey, test != null ? Long.valueOf(testDuration) : null, // testDurationInSeconds autoGranted != null ? Boolean.valueOf(autoGranted) : null, // autoGranted autoGrantedValue != null ? Integer.valueOf(autoGrantedValue) : null // autoGrantedValue ); if (qualType != null) { log.info("Created qualification type: " + qualType.getQualificationTypeId()); FileWriter writer = new FileWriter(propertiesFile + ".success"); try { writer.write(QUALTYPE + System.getProperty("line.separator")); writer.write(qualType.getQualificationTypeId() + System.getProperty("line.separator")); } finally { writer.close(); } log.info("You can take the test here: " + service.getWebsiteURL() + "/mturk/requestqualification?qualificationId=" + qualType.getQualificationTypeId()); return true; } } catch (ParseErrorException parseEx) { try { QAPValidator.validate(test); log.error("The qualification question is not valid: " + parseEx.getLocalizedMessage(), parseEx); } catch (ValidationException valEx) { log.error("The qualification question is not valid: " + valEx.getLocalizedMessage(), valEx); } catch (IOException ioEx) { log.error("The qualification question is not valid: " + parseEx.getLocalizedMessage(), ioEx); } } catch (ObjectAlreadyExistsException exitsEx) { log.error("The qualification type for name '" + qualName + "' already exists.\n"); return false; } catch (Exception e) { log.error("Error creating qualification type: " + e.getLocalizedMessage(), e); return false; } return false; }
From source file:com.ikon.dao.HibernateUtil.java
/** * Replace "create" or "update" by "none" to prevent repository reset on restart *///from w w w . j a v a 2s.co m @SuppressWarnings("unchecked") public static void hibernateCreateAutofix(String configFile) throws IOException { FileReader fr = null; FileWriter fw = null; try { // Open and close reader fr = new FileReader(configFile); List<String> lines = IOUtils.readLines(fr); IOUtils.closeQuietly(fr); // Modify configuration file fw = new FileWriter(configFile); for (String line : lines) { line = line.trim(); int idx = line.indexOf("="); if (idx > -1) { String key = line.substring(0, idx).trim(); String value = line.substring(idx + 1, line.length()).trim(); if (Config.PROPERTY_HIBERNATE_HBM2DDL.equals(key)) { value = HBM2DDL_NONE; } fw.write(key + "=" + value + "\n"); } else { fw.write(line + "\n"); } } fw.flush(); } finally { IOUtils.closeQuietly(fr); IOUtils.closeQuietly(fw); } }
From source file:JSON.WriteProductJSON.java
public int write() { products.put("products", details); try {//from www.j a va 2 s .c o m // Writing to a file File file = new File("Path to products.json"); file.createNewFile(); FileWriter fileWriter = new FileWriter(file); System.out.println("Writing JSON object to file"); System.out.println("-----------------------"); System.out.print(products); fileWriter.write(products.toJSONString()); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } return 0; }
From source file:com.niles.excel2json.objects.ExcelFile.java
public void writeToJson(JSONArray myJSONArray) { String jsFilePath = folderPath + sheetName.replaceAll(" ", "") + ".js"; String jsonFilePath = folderPath + sheetName.replaceAll(" ", "") + ".json"; logger.info("Writing file {}", jsFilePath); try {/*from ww w . ja v a 2 s. c om*/ // Create file FileWriter JSONFileStream = SystemTools.getFileWriter(jsFilePath); JSONFileStream.write("var " + sheetName.replaceAll("-", "").replaceAll(" ", "") + " = " + myJSONArray.toJSONString() + ";"); // JSONFileStream.write(myJSONArray.toJSONString()); JSONFileStream.flush(); JSONFileStream.close(); } catch (IOException ex) { logger.error("[{}] Error writing JSON\r\n{}", jsFilePath, ex.getMessage()); } logger.info("Writing file {}", jsonFilePath); try { // Create file FileWriter JSONFileStream = SystemTools.getFileWriter(jsonFilePath); JSONFileStream.write(myJSONArray.toJSONString()); // JSONFileStream.write(myJSONArray.toJSONString()); JSONFileStream.flush(); JSONFileStream.close(); } catch (IOException ex) { logger.error("[{}] Error writing JSON\r\n{}", jsonFilePath, ex.getMessage()); } }
From source file:com.thoughtworks.go.domain.builder.FetchPluggableArtifactBuilderTest.java
@Test public void shouldCallArtifactExtensionWithMetadata() throws IOException { final FetchPluggableArtifactBuilder builder = new FetchPluggableArtifactBuilder(new RunIfConfigs(), new NullBuilder(), "", jobIdentifier, artifactStore, fetchPluggableArtifactTask.getConfiguration(), fetchPluggableArtifactTask.getArtifactId(), sourceOnServer, metadataDest, checksumFileHandler); final Map<String, Object> metadata = Collections.singletonMap("Version", "10.12.0"); final FileWriter fileWriter = new FileWriter(metadataDest); fileWriter.write(new Gson().toJson(metadata)); fileWriter.close();/*from ww w .ja v a2 s . com*/ builder.build(publisher, new EnvironmentVariableContext(), null, artifactExtension, registry, "utf-8"); verify(artifactExtension).fetchArtifact(eq(PLUGIN_ID), eq(artifactStore), eq(fetchPluggableArtifactTask.getConfiguration()), any(), eq(metadataDest.getParent())); }
From source file:com.crawljax.plugins.adi.Report.java
/** * Save the report as filename./* w ww . j a v a 2 s . com*/ * * @param filename * The file to save the report in. */ public void saveAs(String filename) { File stateFile = new File(filename); try { FileWriter writer = new FileWriter(stateFile, false); writer.write(loadTextFromResource("head.html")); writer.write(addFailuresToDom(controlDom)); writer.write(loadTextFromResource("middle.html")); writer.write(addFailuresToDom(testDom)); writer.write(loadTextFromResource("tail.html")); writer.close(); } catch (Exception e) { e.printStackTrace(); } /* reset failures */ failures = new ArrayList<String[]>(); }
From source file:com.googlecode.fascinator.portal.services.impl.PortalManagerImpl.java
@Override public void save(Portal portal) { String portalName = portal.getName(); File portalFile = new File(new File(portalsDir, FilenameUtils.normalize(portalName)), PORTAL_JSON); portalFile.getParentFile().mkdirs(); try {//from w w w .j av a 2s. c o m FileWriter writer = new FileWriter(portalFile); writer.write(portal.toString(true)); writer.close(); } catch (IOException ioe) { } }
From source file:se.vgregion.portal.cs.util.CryptoUtilImpl.java
/** * Encrypt a value and generate a keyfile. if the keyfile is not found then a new one is created * //ww w . jav a2s . c o m * @param value * - value to be encrypted * @throws GeneralSecurityException * - security exception * @return Encrypted value */ @Override public String encrypt(String value) throws GeneralSecurityException { if (!keyFile.exists()) { KeyGenerator keyGen = KeyGenerator.getInstance(AES); keyGen.init(KEY_SIZE); SecretKey sk = keyGen.generateKey(); FileWriter fw = null; try { fw = new FileWriter(keyFile); fw.write(byteArrayToHexString(sk.getEncoded())); fw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } SecretKeySpec sks = getSecretKeySpec(); Cipher cipher = Cipher.getInstance(AES); cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters()); byte[] encrypted = cipher.doFinal(value.getBytes()); return byteArrayToHexString(encrypted); }