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:br.com.semanticwot.cd.controllers.UserController.java

private void createSettingsNodeRed(SystemUser systemUser) throws SettingsNodeRedNotCreated {
    try {/*from ww  w. ja v a  2 s.c om*/
        File file = new File(System.getProperty("user.home") + System.getProperty("file.separator")
                + Constants.NODERED_PATH + System.getProperty("file.separator") + Constants.SETTINGS_TEMPLATE);

        // O caminho esta correto
        //System.out.println(System.getProperty("user.home")
        //        + System.getProperty("file.separator")
        //        + Constants.NODERED_PATH
        //        + System.getProperty("file.separator")
        //        + Constants.SETTINGS_TEMPLATE);
        // Esta lendo o arquivo de boas
        //System.out.println(new String(Files.readAllBytes(file.toPath())));
        String text = new String(Files.readAllBytes(file.toPath()));

        File formated = new File(
                System.getProperty("user.home") + System.getProperty("file.separator") + Constants.NODERED_PATH
                        + System.getProperty("file.separator") + "settings_" + systemUser.getLogin() + ".js");

        FileWriter fw = new FileWriter(formated.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);

        // Editando o settings_template.js
        if (systemUser.getPerfilstatus().equals(PerfilStatus.PRIVATE)) {
            System.out.println("Entrei em privado");
            text = text.replace("{PROFILE}", "httpNodeAuth: {user:\"{1}\",pass:\"{2}\"},");
        } else {
            System.out.println("Entrei em publico");
            text = text.replace("{PROFILE}", "");
        }

        text = text.replace("{0}", String.valueOf(systemUser.getPort()));
        text = text.replace("{1}", systemUser.getLogin());
        text = text.replace("{2}", systemUser.getPassword());

        bw.write(text);
        bw.close();

    } catch (IOException ex) {
        Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        throw new SettingsNodeRedNotCreated("Settings not created");
    }

}

From source file:eu.mihosoft.vrl.fxscad.MainController.java

@FXML
private void onLoadFile(ActionEvent e) {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Open JFXScad File");
    fileChooser.getExtensionFilters().add(
            new FileChooser.ExtensionFilter("JFXScad files (*.jfxscad, *.groovy)", "*.jfxscad", "*.groovy"));

    File f = fileChooser.showOpenDialog(null);

    if (f == null) {
        return;/*ww  w.j av  a 2  s.c  om*/
    }

    String fName = f.getAbsolutePath();

    if (!fName.toLowerCase().endsWith(".groovy") && !fName.toLowerCase().endsWith(".jfxscad")) {
        fName += ".jfxscad";
    }

    try {
        setCode(new String(Files.readAllBytes(Paths.get(fName)), "UTF-8"));
    } catch (IOException ex) {
        Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.twosigma.beaker.core.rest.FileIORest.java

private String readAsString(String path) {
    try {//from  w  ww  . ja  va  2  s.  c om
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString();
    } catch (AccessDeniedException ade) {
        throw new FileAccessDeniedException(ExceptionUtils.getMessage(ade));
    } catch (Throwable t) {
        throw new FileOpenException(ExceptionUtils.getStackTrace(t));
    }
}

From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java

@Test
public void testWriteLinesToPath() throws IOException {
    Iterable<String> lines = ImmutableList.of("foo", "bar", "baz");
    filesystem.writeLinesToPath(lines, Paths.get("lines.txt"));

    String contents = new String(Files.readAllBytes(tmp.getRoot().resolve("lines.txt")), UTF_8);
    assertEquals("foo\nbar\nbaz\n", contents);
}

From source file:de.alpharogroup.crypto.key.KeyExtensions.java

/**
 * reads a public key from a file.//from   w  w  w. j  av  a  2 s .c o  m
 *
 * @param file
 *            the file
 * @param securityProvider
 *            the security provider
 * @return the public key
 * @throws Exception
 *             is thrown if if a security error occur
 */
public static PublicKey readPemPublicKey(final File file, final SecurityProvider securityProvider)
        throws Exception {
    final byte[] keyBytes = Files.readAllBytes(file.toPath());
    final String publicKeyAsString = new String(keyBytes).replace(BEGIN_PUBLIC_KEY_PREFIX, "")
            .replace(END_PUBLIC_KEY_SUFFIX, "");
    final byte[] decoded = Base64.decodeBase64(publicKeyAsString);
    return readPublicKey(decoded, securityProvider);
}

From source file:com.yahoo.parsec.gradle.utils.FileUtils.java

/**
 * get file content./*from  w  ww  . ja  v  a 2s  .  c  o  m*/
 * @param filePath file path
 * @return file content
 * @throws IOException io exception
 */
public String getFileContent(final Path filePath) throws IOException {
    return new String(Files.readAllBytes(filePath));
}

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

@Override
public void importCSV(String inputFile) {
    try {// w  ww .ja v  a 2  s.  c o  m
        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) {
            Match match = new Match();
            match.setId(Integer.parseInt(record.get(0)));
            match.setMatchNum(Integer.parseInt(record.get(1)));
            match.setTeam(Integer.parseInt(record.get(2)));
            match.setScore(Integer.parseInt(record.get(3)));
            String[] tags = record.get(4).substring(1, record.get(4).length() - 1).split(",");
            for (int i = 0; i < tags.length; i++)
                tags[i] = tags[i].trim();
            if (tags.length > 0 && !tags[0].equals(""))
                match.setTags(Arrays.asList(tags));
            else
                match.setTags(new ArrayList<String>());
            if (checkForMatch(match.getMatchNum(), match.getTeam()))
                update(match);
            else
                create(match);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.projectbuendia.openmrs.web.controller.ProfileManager.java

/** Downloads a profile. */
private void downloadProfile(File file, HttpServletResponse response) {
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
    try {//w  ww .ja v a 2s.  c o  m
        response.getOutputStream().write(Files.readAllBytes(Paths.get(file.getAbsolutePath())));
    } catch (IOException e) {
        log.error("Error downloading profile: " + file.getName(), e);
    }
}

From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java

@Test
public void testWriteBytesToPath() throws IOException {
    String content = "Hello, World!";
    byte[] bytes = content.getBytes(UTF_8);
    filesystem.writeBytesToPath(bytes, Paths.get("hello.txt"));
    assertEquals(content, new String(Files.readAllBytes(tmp.getRoot().resolve("hello.txt")), UTF_8));
}

From source file:org.schedulesdirect.grabber.ScheduleTask.java

protected Map<String, Collection<String>> getStaleStationIds() {
    Map<String, Collection<String>> staleIds = new HashMap<>();
    DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.SCHEDULE_MD5S,
            clnt.getHash(), clnt.getUserAgent(), clnt.getBaseUrl());
    JSONArray data = new JSONArray();
    for (int i = 0; i < this.req.length(); ++i) {
        JSONObject o = new JSONObject();
        o.put("stationID", this.req.getString(i));
        data.put(o);/*from ww w . j  a v  a 2s . co m*/
    }
    try {
        JSONObject result = Config.get().getObjectMapper().readValue(req.submitForJson(data), JSONObject.class);
        if (!JsonResponseUtils.isErrorResponse(result)) {
            Iterator<?> idItr = result.keys();
            while (idItr.hasNext()) {
                String stationId = idItr.next().toString();
                boolean schedFileExists = Files
                        .exists(vfs.getPath("schedules", String.format("%s.txt", stationId)));
                Path cachedMd5File = vfs.getPath("md5s", String.format("%s.txt", stationId));
                JSONObject cachedMd5s = Files.exists(cachedMd5File)
                        ? Config.get().getObjectMapper()
                                .readValue(new String(Files.readAllBytes(cachedMd5File),
                                        ZipEpgClient.ZIP_CHARSET.toString()), JSONObject.class)
                        : new JSONObject();
                JSONObject stationInfo = result.getJSONObject(stationId);
                Iterator<?> dateItr = stationInfo.keys();
                while (dateItr.hasNext()) {
                    String date = dateItr.next().toString();
                    JSONObject dateInfo = stationInfo.getJSONObject(date);
                    if (!schedFileExists || isScheduleStale(dateInfo, cachedMd5s.optJSONObject(date))) {
                        Collection<String> dates = staleIds.get(stationId);
                        if (dates == null) {
                            dates = new ArrayList<String>();
                            staleIds.put(stationId, dates);
                        }
                        dates.add(date);
                        if (LOG.isDebugEnabled())
                            LOG.debug(String.format("Station %s/%s queued for refresh!", stationId, date));
                    } else if (LOG.isDebugEnabled())
                        LOG.debug(String.format("Station %s is unchanged on the server; skipping it!",
                                stationId));
                }
                Files.write(cachedMd5File, stationInfo.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET),
                        StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING,
                        StandardOpenOption.CREATE);
            }
        }
    } catch (Throwable t) {
        Grabber.failedTask = true;
        LOG.error("Error processing cache; returning partial stale list!", t);
    }
    return staleIds;
}