Example usage for java.nio.file Files write

List of usage examples for java.nio.file Files write

Introduction

In this page you can find the example usage for java.nio.file Files write.

Prototype

public static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options)
        throws IOException 

Source Link

Document

Write lines of text to a file.

Usage

From source file:deincraftlauncher.InstallController.java

private void saveConfig() {

    String newln = System.getProperty("line.separator");
    String Texts[] = new String[2];
    Texts[0] = "Deincraft Config 1.0";
    Texts[1] = targetPath;//from w  ww. ja v  a  2 s  .  c o m

    String toWrite = "";
    for (String Text : Texts) {
        toWrite += Text + newln;
    }

    try {
        Files.write(Paths.get(config.toString()), toWrite.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

From source file:org.apache.flink.yarn.CliFrontendYarnAddressConfigurationTest.java

private File writeYarnPropertiesFile(String contents) throws IOException {
    File tmpFolder = temporaryFolder.newFolder();
    String currentUser = System.getProperty("user.name");

    // copy .yarn-properties-<username>
    File testPropertiesFile = new File(tmpFolder, ".yarn-properties-" + currentUser);
    Files.write(testPropertiesFile.toPath(), contents.getBytes(), StandardOpenOption.CREATE);

    // copy reference flink-conf.yaml to temporary test directory and append custom configuration path.
    String confFile = flinkConf + "\nyarn.properties-file.location: " + tmpFolder;
    File testConfFile = new File(tmpFolder.getAbsolutePath(), "flink-conf.yaml");
    Files.write(testConfFile.toPath(), confFile.getBytes(), StandardOpenOption.CREATE);

    return tmpFolder.getAbsoluteFile();
}

From source file:com.oneops.inductor.InductorTest.java

/**
 * This could be used for local testing, Need to add key and modify the user-app.json accordingly
 *///w  w w  . j  av a 2s.  c  om
//@Test
public void runVerification() throws IOException {
    CmsWorkOrderSimple wo = gson.fromJson(remoteWo, CmsWorkOrderSimple.class);
    Config cfg = new Config();
    cfg.setCircuitDir("/opt/oneops/inductor/packer");
    cfg.setIpAttribute("public_ip");
    cfg.setDataDir("/tmp/wos");
    cfg.setVerifyMode(true);
    cfg.setClouds(Collections.EMPTY_LIST);

    String privKey = readResourceAsString("/verification/key");
    wo.getPayLoadEntryAt(SECURED_BY, 0).getCiAttributes().put(PRIVATE, privKey);
    wo.getPayLoad().get(MANAGED_VIA).get(0).setCiAttributes(Collections.singletonMap("public_ip", ""));
    wo.getRfcCi().setCiName("app-7401500-1");
    WorkOrderExecutor executor = new WorkOrderExecutor(cfg, mock(Semaphore.class));
    HashMap<String, CmsWorkOrderSimple> hm = new HashMap<>();
    hm.put("workorder", wo);
    byte[] userWO = readResourceAsBytes("user-app.json");

    Files.write(Paths.get("/tmp/wos/190494.json"), userWO, TRUNCATE_EXISTING);
    Map<String, String> mp = new HashMap<>();
    executor.runVerification(wo, mp);
}

From source file:org.ballerinalang.test.packaging.ModuleBuildTestCase.java

/**
 * Building an empty project without any modules.
 *
 * @throws BallerinaTestException When an error occurs executing the command.
 *///  w ww. j av  a 2 s  .  c om
@Test(description = "Test building a project with an invalid manifest file")
public void testBuildOnInvalidManifest() throws BallerinaTestException, IOException {
    Path projectPath = tempProjectDirectory.resolve("invalidManifest");
    initProject(projectPath, EMPTY_PROJECT_OPTS);

    String invalidContent = "[project]\n org-name = \"integrationtests\"\n version = \"1.0.0";
    Files.write(projectPath.resolve("Ballerina.toml"), invalidContent.getBytes(),
            StandardOpenOption.TRUNCATE_EXISTING);

    LogLeecher clientLeecher = new LogLeecher("error: invalid toml syntax at Ballerina.toml:3",
            LogLeecher.LeecherType.ERROR);
    balClient.runMain("build", new String[0], envVariables, new String[0], new LogLeecher[] { clientLeecher },
            projectPath.toString());
    clientLeecher.waitForText(3000);
}

From source file:io.adeptj.runtime.server.Server.java

private void createServerConfFile() {
    try (InputStream stream = Server.class.getResourceAsStream("/reference.conf")) {
        Files.write(Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE),
                IOUtils.toBytes(stream), StandardOpenOption.CREATE);
    } catch (IOException ex) {
        LOGGER.error("Exception while creating server conf file!!", ex);
    }/*  ww  w. j av  a 2  s  . c o m*/
}

From source file:com.bombardier.plugin.utils.FilePathUtils.java

/**
 * Used to write each test case to a file line by line.
 * //from w  ww  .  j  av  a  2  s  . com
 * @param path
 *            The {@link Path} to the file
 * @param lines
 *            the list of lines to be written
 * @return the path to the file
 * @throws IOException
 * @throws InterruptedException
 * @since 1.0
 */
public static Path writeToTextFile(FilePath filePath, List<String> lines)
        throws IOException, InterruptedException {
    return Files.write(Paths.get(filePath.absolutize().toURI()), lines, StandardCharsets.UTF_8);
}

From source file:org.fim.internal.hash.FileHasherTest.java

private Path createFileWithSize(int fileSize) throws IOException {
    Path newFile = context.getRepositoryRootDir().resolve("file_" + fileSize);
    if (Files.exists(newFile)) {
        Files.delete(newFile);/*w  w  w .jav  a 2 s . co  m*/
    }

    if (fileSize == 0) {
        Files.createFile(newFile);
        return newFile;
    }

    try (ByteArrayOutputStream out = new ByteArrayOutputStream(fileSize)) {
        int contentSize = _1_KB / 4;
        int remaining = fileSize;
        for (; remaining > 0; globalSequenceCount++) {
            int size = min(contentSize, remaining);
            byte[] content = generateContent(globalSequenceCount, size);
            remaining -= size;
            out.write(content);
        }

        byte[] fileContent = out.toByteArray();
        assertThat(fileContent.length).isEqualTo(fileSize);
        Files.write(newFile, fileContent, CREATE);
    }

    return newFile;
}

From source file:faescapeplan.FAEscapePlanUI.java

@SuppressWarnings("unchecked")
private void downloadJournals(ArrayList<String> journalList) {
    JSONArray jsonList = new JSONArray();
    String downloadLoc = this.saveLocText.getText();
    Path jsonPath = Paths.get(downloadLoc + "\\" + userData.getName() + "\\journals\\journals.json");

    try {/*w  w w  . j  a  v a2  s.c  om*/
        Files.deleteIfExists(jsonPath);
        Files.createFile(jsonPath);
    } catch (IOException ex) {
        Logger.getLogger(FAEscapePlanUI.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(this, "A critical IO exception occurred in method: downloadJournals");
    }

    for (String item : journalList) {
        try {
            Map<String, String> jsonMap = new LinkedHashMap<>();
            Document doc = Jsoup.connect("http://www.furaffinity.net/journal/" + item + "/")
                    .cookies(userData.getCookies()).userAgent(USER_AGENT).get();
            String title = doc.title().split(" -- ")[0];
            String date = doc.getElementsByClass("popup_date").get(0).attr("title");
            String body = doc.getElementsByClass("journal-body").get(0).html();
            jsonMap.put("title", title);
            jsonMap.put("date", date);
            jsonMap.put("body", body);
            jsonList.add(jsonMap);
            Path journalPath = Paths.get(downloadLoc,
                    "\\" + userData.getName() + "\\journals\\" + item + "_" + title + ".txt");
            String bodyParsed = removeHtmlTags(body);

            try (FileWriter journalWriter = new FileWriter(new File(journalPath.toString()))) {
                journalWriter.append(title + System.getProperty("line.separator"));
                journalWriter.append(date + System.getProperty("line.separator"));
                journalWriter.append(bodyParsed + System.getProperty("line.separator"));
            }
        } catch (FileAlreadyExistsException ex) {
            Logger.getLogger(FAEscapePlanUI.class.getName()).log(Level.SEVERE, null, ex);
            updateTextLog("File already exists");
        } catch (IOException ex) {
            Logger.getLogger(FAEscapePlanUI.class.getName()).log(Level.SEVERE, null, ex);
            updateTextLog("An IO Exception occurred while downloading journal: " + item);
        }
    }

    String jsonString = JSONValue.toJSONString(jsonList);

    try {
        Files.write(jsonPath, Arrays.asList(jsonString), StandardOpenOption.WRITE);
    } catch (IOException ex) {
        Logger.getLogger(FAEscapePlanUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.openbaton.vnfm.generic.GenericVNFM.java

private void saveLogToFile(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, String script,
        VNFCInstance vnfcInstance1, String output, boolean error) throws IOException {
    if (this.old > 0) {
        String path = "";
        if (!error) {
            path = this.scriptsLogPath + virtualNetworkFunctionRecord.getName() + "/"
                    + vnfcInstance1.getHostname() + ".log";
        } else {// w  w  w  .j  av  a 2s .  c om
            path = this.scriptsLogPath + virtualNetworkFunctionRecord.getName() + "/"
                    + vnfcInstance1.getHostname() + "-error.log";
        }
        File f = new File(path);

        if (!f.exists()) {
            f.getParentFile().mkdirs();
            f.createNewFile();
        }

        if (!error) {
            Files.write(Paths.get(path), ("Output of Script : " + script + "\n\n").getBytes(),
                    StandardOpenOption.APPEND);
            Files.write(Paths.get(path), this.parser.fromJson(output, JsonObject.class).get("output")
                    .getAsString().replaceAll("\\\\n", "\n").getBytes(), StandardOpenOption.APPEND);
        } else {
            Files.write(Paths.get(path), ("Error log of Script : " + script + "\n\n").getBytes(),
                    StandardOpenOption.APPEND);
            Files.write(Paths.get(path), this.parser.fromJson(output, JsonObject.class).get("err").getAsString()
                    .replaceAll("\\\\n", "\n").getBytes(), StandardOpenOption.APPEND);
        }
        Files.write(Paths.get(path),
                "\n\n\n~~~~~~~~~~~~~~~~~~~~~~~~~\n#########################\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n"
                        .getBytes(),
                StandardOpenOption.APPEND);
    }
}

From source file:entity.service.EntryFacadeREST.java

@POST
@Path("/processcsv/{raceid}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces("application/json; charset=UTF-8")
public Response processCSV(@FormParam("filename") String fileName, @PathParam("raceid") Integer raceid) {
    parameters.initClubs();//from   w  ww.ja  va2  s  .  c  o m
    List<String> invalidLicences = new ArrayList<>();
    invalidLicences.add("nev;rajtszam;licensz");
    try (Reader in = new InputStreamReader(
            new FileInputStream(appParameters.getProperty("uploadFolder") + fileName), "UTF-8")) {
        Iterable<CSVRecord> records = CSVFormat.EXCEL.withSkipHeaderRecord().withDelimiter(';')
                .withHeader(CSV_HEADERS).withNullString("").parse(in);
        int count = 0;
        for (CSVRecord record : records) {
            EntryData ed = new EntryData();
            ed.setPreentry(true);
            ed.setStatus("PRE");
            ed.setName(record.get("name"));
            ed.setRacenum(record.get("racenum"));
            ed.setGender(record.get("gender"));
            ed.setBirthYear(Short.valueOf(record.get("birthyear")));
            ed.setCategory(record.get("category"));
            ed.setFromTown(record.get("fromtown"));
            ed.setClubName(record.get("club"));
            ed.setAgegroup(record.get("agegroup"));
            ed.setPaid(record.get("paid").equals("IGEN"));
            ed.setRemainingpayment(
                    record.get("paid").matches("[1-9]\\d{0,10}") ? Integer.parseInt(record.get("paid")) : 0);
            ed.setLicencenum(record.get("licencenum"));
            if (ed.getLicencenum() != null && !ed.getLicencenum().isEmpty()) {
                if (!licenceFacade.exists(ed.getLicencenum())) {
                    invalidLicences.add(ed.getName() + ";" + ed.getRacenum() + ";" + ed.getLicencenum());
                }
            }
            insertEntry(ed, raceid);
            ++count;
        }
        String invalidLicencesFileName = "invalid_licences_" + fileName;
        Files.write(Paths.get(appParameters.getProperty("uploadFolder"), invalidLicencesFileName),
                invalidLicences, Charset.forName("UTF-8"));
        HashMap<String, Object> params = new HashMap<>();
        params.put("invalidLicences", invalidLicencesFileName);
        JsonObject jsonMsg = JsonBuilder.getJsonMsg(count + " db elnevezs beolvasva!",
                JsonBuilder.MsgType.INFO, params);
        return Response.ok(String.valueOf(jsonMsg)).build();
    } catch (FileNotFoundException ex) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("fileName", fileName);
        JsonObject jsonMsg = JsonBuilder.getJsonMsg("A megadott fjl nem tallhat!",
                JsonBuilder.MsgType.ERROR, params);
        return Response.status(500).entity(jsonMsg).build();
    } catch (IOException ex) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("fileName", fileName);
        JsonObject jsonMsg = JsonBuilder.getJsonMsg("Hiba a CSV fjl beolvassa kzben!",
                JsonBuilder.MsgType.ERROR, params);
        return Response.status(500).entity(jsonMsg).build();
    }
}