Example usage for java.nio.file Files readAllBytes

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

Introduction

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

Prototype

public static byte[] readAllBytes(Path path) throws IOException 

Source Link

Document

Reads all the bytes from a file.

Usage

From source file:com.collective.celos.ci.deploy.WorkflowFilesDeployerTest.java

private String readFileContent(File fileExists) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(fileExists.toURI()));
    return new String(encoded);
}

From source file:com.payex.utils.formatter.FormatExecutor.java

/**
 * Format individual file.// w  ww .  ja v a  2  s  .  co  m
 * 
 * @param file
 * @param rc
 * @param hashCache
 * @param basedirPath
 * @throws IOException
 * @throws BadLocationException
 */
private void doFormatFile(File file, ResultCollector rc, Properties hashCache, String basedirPath)
        throws IOException, BadLocationException {
    log.debug("Processing file: " + file);

    String code = new String(Files.readAllBytes(file.toPath()));// readFileAsString(file);

    String lineSeparator = getLineEnding(code);

    TextEdit te = formatter.format(CodeFormatter.K_COMPILATION_UNIT + CodeFormatter.F_INCLUDE_COMMENTS, code, 0,
            code.length(), 0, lineSeparator);
    if (te == null) {
        rc.skippedCount++;
        log.debug(
                "Code cannot be formatted. Possible cause " + "is unmatched source/target/compliance version.");
        return;
    }

    IDocument doc = new Document(code);
    te.apply(doc);
    String formattedCode = doc.get();

    writeStringToFile(formattedCode, file);
    rc.successCount++;
}

From source file:SDKTest.java

    _ASCII() throws IOException {
    DsmoqClient client = create();//from  w w w.j  ava 2  s .co m
    Path original = Paths.get("testdata", "test.csv");
    Dataset dataset = client.createDataset(true, false, original.toFile());
    String datasetId = dataset.getId();
    RangeSlice<DatasetFile> files = client.getDatasetFiles(datasetId, new GetRangeParam());
    String fileId = files.getResults().get(0).getId();
    byte[] downloaded = client.downloadFile(datasetId, fileId, content -> {
        assertThat(content.getName(), is("test.csv"));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            content.writeTo(bos);
            return bos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
    Assert.assertArrayEquals(downloaded, Files.readAllBytes(original));
}

From source file:com.autodesk.client.ApiClient.java

private ClientResponse getAPIResponse(Credentials credentials, String path, String method,
        List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams,
        String accept, String contentType) throws ApiException {
    if (body != null && !formParams.isEmpty()) {
        throw new ApiException(500, "Cannot have body and form params");
    }/*from www .j a  v  a  2s  .co m*/

    if (body != null && body.getClass().equals(File.class)) {
        try {
            byte[] data = Files.readAllBytes(((File) body).toPath());
            body = data;
            headerParams.put("Content-Length", (new Integer(data.length)).toString());
            contentType = "application/octet-stream";
        } catch (IOException e) {
            throw new ApiException(400, "There was a problem reading the file: " + e.getMessage());
        }
    }

    updateParamsForAuth(credentials, headerParams);

    final String url = buildUrl(path, queryParams);
    Builder builder;
    if (accept == null) {
        builder = httpClient.resource(url).getRequestBuilder();
    } else {
        builder = httpClient.resource(url).accept(accept);
    }

    for (String key : headerParams.keySet()) {
        builder = builder.header(key, headerParams.get(key));
    }
    for (String key : defaultHeaderMap.keySet()) {
        if (!headerParams.containsKey(key)) {
            builder = builder.header(key, defaultHeaderMap.get(key));
        }
    }

    ClientResponse response = null;

    if ("GET".equals(method)) {
        response = (ClientResponse) builder.get(ClientResponse.class);
    } else if ("POST".equals(method)) {
        response = builder.type(contentType).post(ClientResponse.class,
                serialize(body, contentType, formParams));
    } else if ("PUT".equals(method)) {
        response = builder.type(contentType).put(ClientResponse.class,
                serialize(body, contentType, formParams));
    } else if ("DELETE".equals(method)) {
        response = builder.type(contentType).delete(ClientResponse.class,
                serialize(body, contentType, formParams));
    } else if ("PATCH".equals(method)) {
        response = builder.type(contentType).header("X-HTTP-Method-Override", "PATCH")
                .post(ClientResponse.class, serialize(body, contentType, formParams));
    } else {
        throw new ApiException(500, "unknown method type " + method);
    }
    return response;
}

From source file:ch.unibas.charmmtools.gui.step1.mdAssistant.CHARMM_GUI_InputAssistant.java

/**
 * Try to generate an input file with standard parameters, it can be edited later
 *//*from   w ww  .  jav a2s.  c o m*/
@FXML
protected void GenerateInputFile() {

    //        try {
    String folderPath = this.work_directory.getAbsolutePath();

    // get filenames
    //        String corname_gas = ResourceUtils.getRelativePath(textfield_COR_gas.getText(), folderPath);
    //        String corname_liquid = ResourceUtils.getRelativePath(textfield_COR_liquid.getText(), folderPath);
    //        String rtfname = ResourceUtils.getRelativePath(textfield_RTF.getText(), folderPath);
    //        String parname = ResourceUtils.getRelativePath(textfield_PAR.getText(), folderPath);
    //        String lpunname = ResourceUtils.getRelativePath(textfield_LPUN.getText(), folderPath);
    String corname_gas = textfield_COR_gas.getText();
    String corname_liquid = textfield_COR_liquid.getText();
    String rtfname = textfield_RTF.getText();
    String parname = textfield_PAR.getText();
    String lpunname = textfield_LPUN.getText();
    String time = Long.toString(Instant.now().getEpochSecond());

    File gas_vdw_dir = new File(folderPath + "/gas_" + time + "/vdw");
    File gas_mtp_dir = new File(folderPath + "/gas_" + time + "/mtp");
    File solv_vdw_dir = new File(folderPath + "/solv_" + time + "/vdw");
    File solv_mtp_dir = new File(folderPath + "/solv_" + time + "/mtp");

    gas_vdw_dir.mkdirs();
    gas_mtp_dir.mkdirs();
    solv_vdw_dir.mkdirs();
    solv_mtp_dir.mkdirs();
    //        } catch (IOException ex) {
    //            logger.error(ex);
    //        }

    File gasFile = null;
    CHARMM_Input gasInp = null;
    try {
        gasFile = new File(gas_vdw_dir.getParent(), "gas_phase.inp");
        gasInp = new CHARMM_Input_GasPhase(corname_gas, rtfname, parname, lpunname, gasFile);
        tab_list.add(new MyTab("?/H Gas Phase",
                new String(Files.readAllBytes(Paths.get(gasFile.getAbsolutePath())))));
        inp.add(gasInp);
    } catch (IOException ex) {
        logger.error("Error while generating " + gasFile.getAbsolutePath() + " : " + ex);
    }

    File liqFile = null;
    CHARMM_Input liqInp = null;
    try {
        liqFile = new File(solv_vdw_dir.getParent(), "pure_liquid.inp");
        liqInp = new CHARMM_Input_PureLiquid(corname_liquid, rtfname, parname, lpunname, liqFile);
        tab_list.add(new MyTab("?/H Pure Liquid",
                new String(Files.readAllBytes(Paths.get(liqFile.getAbsolutePath())))));
        inp.add(liqInp);
    } catch (IOException ex) {
        logger.error("Error while generating " + liqFile.getAbsolutePath() + " : " + ex);
    }

    //            RedLabel_Notice.setVisible(true);
    String corname_solv = textfield_COR_solv.getText();
    double lamb_spacing_val = Double.valueOf(lambda_space.getText());

    in_gas_vdw = new CHARMM_Generator_DGHydr(corname_gas, rtfname, parname, lpunname, "vdw", 0.0,
            lamb_spacing_val, 1.0, gas_vdw_dir);
    //            CHARMM_inFile.addAll(in_gas_vdw.getMyFiles());
    //
    in_gas_mtp = new CHARMM_Generator_DGHydr(corname_gas, rtfname, parname, lpunname, "mtp", 0.0,
            lamb_spacing_val, 1.0, gas_mtp_dir);
    //            CHARMM_inFile.addAll(in_gas_mtp.getMyFiles());
    //
    in_solv_vdw = new CHARMM_Generator_DGHydr(corname_gas, corname_solv, rtfname, rtfname, parname, lpunname,
            "vdw", 0.0, lamb_spacing_val, 1.0, solv_vdw_dir);
    //            CHARMM_inFile.addAll(in_solv_vdw.getMyFiles());
    //
    in_solv_mtp = new CHARMM_Generator_DGHydr(corname_gas, corname_solv, rtfname, rtfname, parname, lpunname,
            "mtp", 0.0, lamb_spacing_val, 1.0, solv_mtp_dir);

    try {
        for (File fi : in_gas_vdw.getMyFiles()) {
            tab_list.add(
                    new MyTab("Gas & VDW", new String(Files.readAllBytes(Paths.get(fi.getAbsolutePath())))));
        }

        for (File fi : in_gas_mtp.getMyFiles()) {
            tab_list.add(
                    new MyTab("Gas & MTP", new String(Files.readAllBytes(Paths.get(fi.getAbsolutePath())))));
        }

        for (File fi : in_solv_vdw.getMyFiles()) {
            tab_list.add(
                    new MyTab("Solv & VDW", new String(Files.readAllBytes(Paths.get(fi.getAbsolutePath())))));
        }

        for (File fi : in_solv_mtp.getMyFiles()) {
            tab_list.add(
                    new MyTab("Solv & MTP", new String(Files.readAllBytes(Paths.get(fi.getAbsolutePath())))));
        }
    } catch (IOException ex) {
        logger.error("Error while generating DG files : " + ex);
    }

    tab_pane.getTabs().addAll(tab_list);

    button_run_CHARMM.setDisable(false);

    /**
     * If success enable button for saving
     */
    //        button_save_to_file.setDisable(false);
}

From source file:com.team3637.service.TagServiceMySQLImpl.java

@Override
public void importCSV(String inputFile) {
    try {/*from  w ww .  ja va 2s.c om*/
        String csvData = new String(Files.readAllBytes(FileSystems.getDefault().getPath(inputFile)));
        csvData = csvData.replaceAll("\\r", "");
        CSVParser parser = CSVParser.parse(csvData, CSVFormat.DEFAULT.withRecordSeparator("\n"));
        for (CSVRecord record : parser) {
            Tag tag = new Tag();
            tag.setId(Integer.parseInt(record.get(0)));
            tag.setTag(record.get(1));
            tag.setType(record.get(2));
            tag.setCounter(record.get(3));
            tag.setInTable(record.get(4).equals("1") || record.get(4).toLowerCase().equals("true"));
            tag.setRequiesEval(record.get(5).equals("1") || record.get(5).toLowerCase().equals("true"));
            tag.setExpression(record.get(6).replace("\n", ""));
            if (checkForTag(tag))
                update(tag);
            else
                create(tag);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:SDKTest.java

    () throws IOException {
    DsmoqClient client = create();/* w w w . j av a  2  s .co m*/
    Path original = Paths.get("testdata", "test.png");
    Dataset dataset = client.createDataset(true, false, original.toFile());
    String datasetId = dataset.getId();
    RangeSlice<DatasetFile> files = client.getDatasetFiles(datasetId, new GetRangeParam());
    String fileId = files.getResults().get(0).getId();
    byte[] downloaded = client.downloadFile(datasetId, fileId, content -> {
        assertThat(content.getName(), is("test.png"));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            content.writeTo(bos);
            return bos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
    Assert.assertArrayEquals(downloaded, Files.readAllBytes(original));
}

From source file:com.smartsheet.api.internal.SheetResourcesImplTest.java

@Test
public void testGetSheetAsCSV() throws SmartsheetException, IOException {
    File file = new File("src/test/resources/getCsv.csv");
    server.setResponseBody(file);/*from w  w  w .j  a  v  a2  s .  com*/
    server.setContentType("text/csv");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    sheetResource.getSheetAsExcel(1234L, output);

    assertNotNull(output);
    assertTrue(output.toByteArray().length > 0);

    byte[] data = Files.readAllBytes(Paths.get(file.getPath()));
    assertEquals(data.length, output.toByteArray().length);
}

From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java

public final Shops addSell(String shopName, String cost, Player player) {
    try {//from   w w  w  . ja va 2  s  . c  om
        String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json")));

        JSONParser parser = new JSONParser();

        Object obj = parser.parse(configTable);

        JSONObject jsonObj = (JSONObject) obj;

        JSONObject shopObj = (JSONObject) jsonObj.get(shopName);

        // Make sure the shop exists
        if (shopObj == null) {
            player.sendMessage("\u00a76That shop does not exist!");
            return this;
        }

        String newItem = player.getItemInHand().getType().name();

        Bukkit.getLogger()
                .info("Player \"" + player.getDisplayName() + "\" added " + newItem + " to shop " + shopName);

        JSONArray shopItems = (JSONArray) shopObj.get("ShopItems");

        shopItems.add(newItem + ":sell:" + player.getItemInHand().getDurability());

        shopObj.put("ShopItems", shopItems);

        JSONObject itemStub = new JSONObject();
        itemStub.put("amount", Integer.toString(player.getItemInHand().getAmount()));
        itemStub.put("price", cost);
        itemStub.put("type", "sell");
        itemStub.put("durability", "" + player.getItemInHand().getDurability());

        shopObj.put(newItem + ":sell:" + player.getItemInHand().getDurability(), itemStub);

        jsonObj.put(shopName, shopObj);

        // Update Shops.json
        FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json");

        shopsJSON.write(jsonObj.toJSONString());

        shopsJSON.flush();
        shopsJSON.close();

        player.sendMessage("\u00a7aShop updated!");

        return this;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in addSell()");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json");
        e.printStackTrace();
    } catch (IOException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught IOException in addSell()");
        e.printStackTrace();
    }

    return this;
}