List of usage examples for java.nio.file Files newBufferedWriter
public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException
From source file:co.cask.cdap.etl.tool.UpgradeTool.java
private static void convertFile(String configFilePath, String outputFilePath, ArtifactClient artifactClient) throws Exception { File configFile = new File(configFilePath); if (!configFile.exists()) { throw new IllegalArgumentException(configFilePath + " does not exist."); }/* ww w.j a v a 2s . com*/ if (!configFile.isFile()) { throw new IllegalArgumentException(configFilePath + " is not a file."); } String fileContents = new String(Files.readAllBytes(configFile.toPath()), StandardCharsets.UTF_8); ETLAppRequest artifactFile = GSON.fromJson(fileContents, ETLAppRequest.class); if (!shouldUpgrade(artifactFile.artifact)) { throw new IllegalArgumentException("Cannot update for artifact " + artifactFile.artifact + ". " + "Please check the artifact is cdap-etl-batch or cdap-etl-realtime in the system scope of version 3.2.x."); } String version = ETLVersion.getVersion(); File outputFile = new File(outputFilePath); String oldArtifactVersion = artifactFile.artifact.getVersion(); if (BATCH_NAME.equals(artifactFile.artifact.getName())) { ArtifactSummary artifact = new ArtifactSummary(BATCH_NAME, version, ArtifactScope.SYSTEM); UpgradeContext upgradeContext = new BatchClientBasedUpgradeContext(Id.Namespace.DEFAULT, artifactClient); ETLBatchConfig config = convertBatchConfig(oldArtifactVersion, artifactFile.config.toString(), upgradeContext); AppRequest<ETLBatchConfig> updated = new AppRequest<>(artifact, config); try (BufferedWriter writer = Files.newBufferedWriter(outputFile.toPath(), StandardCharsets.UTF_8)) { writer.write(GSON.toJson(updated)); } } else { ArtifactSummary artifact = new ArtifactSummary(REALTIME_NAME, version, ArtifactScope.SYSTEM); UpgradeContext upgradeContext = new RealtimeClientBasedUpgradeContext(Id.Namespace.DEFAULT, artifactClient); ETLRealtimeConfig config = convertRealtimeConfig(oldArtifactVersion, artifactFile.config.toString(), upgradeContext); AppRequest<ETLRealtimeConfig> updated = new AppRequest<>(artifact, config); try (BufferedWriter writer = Files.newBufferedWriter(outputFile.toPath(), StandardCharsets.UTF_8)) { writer.write(GSON.toJson(updated)); } } LOG.info("Successfully converted application details from file " + configFilePath + ". " + "Results have been written to " + outputFilePath); }
From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java
public boolean createCacheFileProteomics(String filePath) { boolean isSuccess = false; JSONObject jsonData = new JSONObject(); JSONObject data;//from w ww . ja v a 2s . c o m // from WP // data data = read(baseURL + "/tab/dlp-proteomics-data/?req=passphrase"); if (data != null) { jsonData.put("data", data); } // tools data = read(baseURL + "/tab/dlp-proteomics-tools/?req=passphrase"); if (data != null) { jsonData.put("tools", data); } // process data = read(baseURL + "/tab/dlp-proteomics-process/?req=passphrase"); if (data != null) { jsonData.put("process", data); } // download data = read(baseURL + "/tab/dlp-proteomics-download/?req=passphrase"); if (data != null) { jsonData.put("download", data); } // save jsonData to file try (PrintWriter jsonOut = new PrintWriter( Files.newBufferedWriter(FileSystems.getDefault().getPath(filePath), Charset.defaultCharset()));) { jsonData.writeJSONString(jsonOut); isSuccess = true; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } return isSuccess; }
From source file:org.zaproxy.zap.extension.quickstart.ExtensionQuickStart.java
private void saveReportTo(Path file) throws Exception { try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { writer.write(getScanReport());//from w ww . j av a 2s.co m } }
From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java
public boolean createCacheFilePPInteractions(String filePath) { boolean isSuccess = false; JSONObject jsonData = new JSONObject(); JSONObject data;//w w w .j a va 2 s. c o m // from WP // data data = read(baseURL + "/tab/dlp-ppinteractions-data/?req=passphrase"); if (data != null) { jsonData.put("data", data); } // tools data = read(baseURL + "/tab/dlp-ppinteractions-tools/?req=passphrase"); if (data != null) { jsonData.put("tools", data); } // process data = read(baseURL + "/tab/dlp-ppinteractions-process/?req=passphrase"); if (data != null) { jsonData.put("process", data); } // download data = read(baseURL + "/tab/dlp-ppinteractions-download/?req=passphrase"); if (data != null) { jsonData.put("download", data); } // save jsonData to file try (PrintWriter jsonOut = new PrintWriter( Files.newBufferedWriter(FileSystems.getDefault().getPath(filePath), Charset.defaultCharset()));) { jsonData.writeJSONString(jsonOut); isSuccess = true; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } return isSuccess; }
From source file:popgenutils.dfcp.PrepareVCF4DFCP.java
/** * /*from ww w .jav a 2 s. c om*/ */ private void mask() { StringBuilder header = new StringBuilder(); try (BufferedReader in = Files.newBufferedReader(Paths.get(filename), Charset.forName("UTF-8"))) { BufferedWriter out = null; String line = null; int number_of_individuals = 0; Set<Integer> individuals_to_genotype = new HashSet<Integer>(); while ((line = in.readLine()) != null) { if (line.startsWith("#CHROM")) { //samples begin at 9 number_of_individuals = line.split("\t").length - 9; List<Integer> index_of_individuals = new ArrayList<Integer>(); for (int i = 0; i < number_of_individuals; i++) { index_of_individuals.add(i); } Collections.shuffle(index_of_individuals); if (pmask >= 0) { // convert pgeno into ageno amask = (int) Math.ceil(number_of_individuals * pmask); } for (int i = 0; i < amask; i++) { individuals_to_genotype.add(index_of_individuals.get(i)); } out = Files.newBufferedWriter( Paths.get(output_dir + "/" + amask + "_mask" + Paths.get(filename).getFileName()), Charset.forName("UTF-8")); out.write(header.toString()); out.write(line + System.getProperty("line.separator")); } else if (line.startsWith("#")) { header.append(line + System.getProperty("line.separator")); } else { // format at 8 String[] parts = line.split("\t"); String[] parts2 = parts[8].split(":"); int gt_pos = 0; for (int i = 1; i < parts2.length; i++) { if (parts2[i].equals("GT")) gt_pos = i; } out.write(parts[0]); for (int i = 1; i < parts.length; i++) { if (i > 8) { parts2 = parts[i].split(":"); if (gt_pos == 0 && individuals_to_genotype.contains(i - 8)) { out.write("\t" + maskAlleles(parts2[0])); } else out.write(parts2[0]); for (int j = 1; j < parts2.length; j++) { if (gt_pos == j && individuals_to_genotype.contains(i - 8)) { out.write(":" + maskAlleles(parts2[i])); } else out.write(":" + parts2[i]); } } else { out.write("\t" + parts[i]); } } out.write(System.getProperty("line.separator")); } } } catch (IOException e) { System.err.println("could not read from file " + filename); e.printStackTrace(); } }
From source file:eu.itesla_project.eurostag.EurostagImpactAnalysis.java
private void writeWp43Configs(List<Contingency> contingencies, Path workingDir) throws IOException, ConfigurationException { Path baseWp43ConfigFile = PlatformConfig.CONFIG_DIR.resolve(WP43_CONFIGS_FILE_NAME); // generate one variant of the base config for all the contingency // this allow to add extra variables for some indexes HierarchicalINIConfiguration configuration = new HierarchicalINIConfiguration(baseWp43ConfigFile.toFile()); SubnodeConfiguration node = configuration.getSection("smallsignal"); node.setProperty("f_instant", parameters.getFaultEventInstant()); for (int i = 0; i < contingencies.size(); i++) { Contingency contingency = contingencies.get(i); if (contingency.getElements().isEmpty()) { throw new AssertionError("Empty contingency " + contingency.getId()); }/*from www . ja v a 2s . c o m*/ Iterator<ContingencyElement> it = contingency.getElements().iterator(); // compute the maximum fault duration double maxDuration = getFaultDuration(contingency, it.next()); while (it.hasNext()) { maxDuration = Math.max(maxDuration, getFaultDuration(contingency, it.next())); } node.setProperty("f_duration", maxDuration); Path wp43Config = workingDir.resolve(WP43_CONFIGS_PER_FAULT_FILE_NAME .replace(Command.EXECUTION_NUMBER_PATTERN, Integer.toString(i))); try (Writer writer = Files.newBufferedWriter(wp43Config, StandardCharsets.UTF_8)) { configuration.save(writer); } } }
From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java
public boolean createCacheFilePathways(String filePath) { boolean isSuccess = false; JSONObject jsonData = new JSONObject(); JSONObject data;/*from w w w . ja v a 2 s . co m*/ // from WP // data data = read(baseURL + "/tab/dlp-pathways-data/?req=passphrase"); if (data != null) { jsonData.put("data", data); } // conservation data = getPathwayECDist(); if (data != null) { jsonData.put("conservation", data); } // popular genomes data = getPopularGenomesForPathways(); if (data != null) { jsonData.put("popularGenomes", data); } // tools data = read(baseURL + "/tab/dlp-pathways-tools/?req=passphrase"); if (data != null) { jsonData.put("tools", data); } // process data = read(baseURL + "/tab/dlp-pathways-process/?req=passphrase"); if (data != null) { jsonData.put("process", data); } // download data = read(baseURL + "/tab/dlp-pathways-download/?req=passphrase"); if (data != null) { jsonData.put("download", data); } // save jsonData to file try (PrintWriter jsonOut = new PrintWriter( Files.newBufferedWriter(FileSystems.getDefault().getPath(filePath), Charset.defaultCharset()));) { jsonData.writeJSONString(jsonOut); isSuccess = true; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } return isSuccess; }
From source file:vn.edu.vnu.uet.nlp.smt.ibm.IBMModel3.java
@Override public void save(String folder) throws IOException { super.save(folder); File fol = new File(folder); if (!fol.isDirectory()) { System.err.println(folder + " is not a folder! Cannot save model!"); return;/* w ww . j av a 2s .c om*/ } if (!folder.endsWith("/")) { folder = folder + "/"; } // Save distortion String dFileName = folder + IConstants.distortionModelName; Utils.saveArray(d, maxLe, maxLf, maxLe, maxLf, dFileName, iStart); // Save fertility String nFileName = folder + IConstants.fertilityModelName; Utils.saveObject(n, nFileName); // Save null insertion String nullInsertionFileName = folder + IConstants.nullInsertionModelName; BufferedWriter bw = Files.newBufferedWriter(Paths.get(nullInsertionFileName), StandardOpenOption.CREATE); bw.write("p0 = " + p0); bw.flush(); bw.close(); }
From source file:misc.FileHandler.java
/** * Writes the given synchronization version to the version file which * belongs to the given file name. The version file is created, if it does * not exist yet. Returns whether the version file was successfully written. * /*from w w w .java 2s . c om*/ * @param version * the version number up to which all actions have been executed. * Must be at least <code>0</code>. * @param clientRoot * the complete path to the client's root directory. Must exist. * @param syncRoot * the complete path to the synchronization root directory. Must * exist. * @param pathLocal * the local path to synchronize containing an access bundle. * Must be relative to <code>clientRoot</code>. May not be * <code>null</code>. * @return <code>true</code>, if the version file was successfully written. * Otherwise, <code>false</code>. */ public static boolean writeVersion(int version, Path clientRoot, Path syncRoot, Path pathLocal) { if (version < 0) { throw new IllegalArgumentException("version must be at least 0!"); } if ((clientRoot == null) || !Files.isDirectory(clientRoot)) { throw new IllegalArgumentException("clientRoot must be an existing directory!"); } if ((syncRoot == null) || !Files.isDirectory(syncRoot)) { throw new IllegalArgumentException("syncRoot must be an existing directory!"); } if (pathLocal == null) { throw new NullPointerException("pathLocal may not be null!"); } boolean success = false; Path arbitraryFileName = Paths.get(pathLocal.toString(), "arbitrary"); Path accessBundleDirectory = FileHandler.getAccessBundleDirectory(clientRoot, arbitraryFileName); if (accessBundleDirectory != null) { Path versionFile = Paths.get(syncRoot.toString(), accessBundleDirectory.toString(), SynchronizationExecutor.VERSION_FILE); FileHandler.makeParentDirs(versionFile); /* * Write the new version into a temporary file and rename it to the * version file. */ Path tempFile = FileHandler.getTempFile(versionFile); if (tempFile != null) { try (BufferedWriter writer = Files.newBufferedWriter(tempFile, Coder.CHARSET);) { writer.write(String.valueOf(version)); writer.write('\n'); writer.flush(); Files.move(tempFile, versionFile, StandardCopyOption.REPLACE_EXISTING); success = true; } catch (IOException e) { Logger.logError(e); } finally { if (tempFile != null) { try { Files.deleteIfExists(tempFile); } catch (IOException e) { Logger.logError(e); } } } } } return success; }
From source file:net.sourceforge.pmd.util.designer.Designer.java
private void saveSettings() { try {/*from w ww .jav a 2s . c o m*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element settingsElement = document.createElement("settings"); document.appendChild(settingsElement); Element codeElement = document.createElement("code"); settingsElement.appendChild(codeElement); codeElement.setAttribute("language-version", getLanguageVersion().getTerseName()); codeElement.appendChild(document.createCDATASection(codeEditorPane.getText())); Element xpathElement = document.createElement("xpath"); settingsElement.appendChild(xpathElement); xpathElement.setAttribute("version", xpathVersionButtonGroup.getSelection().getActionCommand()); xpathElement.appendChild(document.createCDATASection(xpathQueryArea.getText())); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // This is as close to pretty printing as we'll get using standard // Java APIs. transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); Source source = new DOMSource(document); Result result = new StreamResult( Files.newBufferedWriter(new File(SETTINGS_FILE_NAME).toPath(), StandardCharsets.UTF_8)); transformer.transform(source, result); } catch (ParserConfigurationException | IOException | TransformerException e) { e.printStackTrace(); } }