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:ch.unibas.fittingwizard.application.tools.Notifications.java

private void sendErrorLogByMail() {
    try {/*from w ww  . ja  va 2 s  .c o m*/
        Email email = new SimpleEmail();
        email.setMailSession(Session.getDefaultInstance(props));

        email.setSubject("Log of FW session");
        email.setMsg(new String(Files.readAllBytes(Paths.get("fw-log.txt"))));
        email.setFrom(getSender().trim());
        email.addTo(getRecipient().trim());

        email.send();
    } catch (IOException | EmailException e) {
        throw new RuntimeException("Could not send notification.", e);
    }
}

From source file:com.baeldung.file.FileOperationsTest.java

@Test
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
    String expectedData = "Hello World from fileTest.txt!!!";

    Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());

    byte[] fileBytes = Files.readAllBytes(path);
    String data = new String(fileBytes);

    Assert.assertEquals(expectedData, data.trim());
}

From source file:at.ac.tuwien.qse.sepm.service.impl.ExportServiceImpl.java

@Override
public String getDropboxFolder() {
    Path dropboxInfoPath = getDropboxInfoPath();

    LOGGER.debug("dropbox info path is {}", dropboxInfoPath);

    if (dropboxInfoPath == null) {
        return null;
    }//ww w.  j  av  a2  s . co  m

    String info;
    try {
        LOGGER.debug("reading dropbox info file");
        info = new String(Files.readAllBytes(dropboxInfoPath));
        LOGGER.debug("read dropbox info file");
    } catch (IOException ex) {
        LOGGER.error("Failed to read dropbox configuration file", ex);
        return null;
    }

    try {
        LOGGER.debug("parsing dropbox info file to JSON");
        JSONObject obj = new JSONObject(info);
        String dropboxPath = obj.getJSONObject("personal").getString("path");
        LOGGER.debug("found dropbox path as {}", dropboxPath);
        return dropboxPath;
    } catch (JSONException ex) {
        LOGGER.error("Failed to retrieve dropbox folder location", ex);
        return null;
    }
}

From source file:com.nexmo.client.auth.JWTAuthMethod.java

public JWTAuthMethod(String applicationId, Path path)
        throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, IOException {
    this(applicationId, Files.readAllBytes(path));
}

From source file:adminShop.registraProducto.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  www.  j av  a2 s .c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String message = "Error";
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items;
        HashMap hm = new HashMap();
        ArrayList<Imagen> imgs = new ArrayList<>();
        Producto prod = new Producto();
        Imagen img = null;
        try {
            items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString();
                    hm.put(name, value);
                } else {
                    img = new Imagen();
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeBytes = item.getSize();
                    File file = new File("/home/gama/Escritorio/adoo/" + fileName + ".jpg");
                    item.write(file);
                    Path path = Paths.get("/home/gama/Escritorio/adoo/" + fileName + ".jpg");
                    byte[] data = Files.readAllBytes(path);
                    byte[] encode = org.apache.commons.codec.binary.Base64.encodeBase64(data);
                    img.setUrl(new javax.sql.rowset.serial.SerialBlob(encode));
                    imgs.add(img);
                    //file.delete();
                }
            }
            prod.setNombre((String) hm.get("nombre"));
            prod.setProdNum((String) hm.get("prodNum"));
            prod.setDesc((String) hm.get("desc"));
            prod.setIva(Double.parseDouble((String) hm.get("iva")));
            prod.setPrecio(Double.parseDouble((String) hm.get("precio")));
            prod.setPiezas(Integer.parseInt((String) hm.get("piezas")));
            prod.setEstatus("A");
            prod.setImagenes(imgs);
            ProductoDAO prodDAO = new ProductoDAO();
            if (prodDAO.registraProducto(prod)) {
                message = "Exito";
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    response.sendRedirect("index.jsp");
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGeneratorSmokeTest.java

@After
public void tearDown() throws IOException {
    // Dump the contents of the file system
    Path dumpStart = fs.getPath("/");
    Files.walkFileTree(dumpStart, new SimpleFileVisitor<Path>() {
        @Override/*from w ww.j a  v a  2s.  co  m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println("> " + file);
            System.out.println(new String(Files.readAllBytes(file), StandardCharsets.UTF_8));

            // Copy the file if wanted
            if (DUMP_DIRECTORY != null) {
                Path dumpTarget = Paths.get(DUMP_DIRECTORY, name.getMethodName());
                Path target = dumpTarget.resolve(dumpStart.relativize(file).toString());
                Files.createDirectories(target.getParent());
                Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:ru.jts_dev.gameserver.parser.html.HtmlRepository.java

private String readHtml(Locale language, String htmlName) {
    Path htmlPath = htmlDir.resolve(language.toLanguageTag()).resolve(htmlName);
    if (!Files.exists(htmlPath)) {
        throw new IllegalArgumentException("Can't find html: " + htmlPath);
    }//from www  . j  a  v  a2s  .  co  m
    try {
        byte[] content = Files.readAllBytes(htmlPath);
        return new String(content, UTF_8);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:bit.changepurse.wdk.util.CheckedExceptionMethods.java

public static String readTextFile(Path path) {
    try {/*from  w  ww  .ja v a  2s . c om*/
        return new String(Files.readAllBytes(path));
    } catch (IOException e) {
        throw new UncheckedException(e);
    }
}

From source file:com.netease.hearttouch.hthotfix.patch.PatchSoHelper.java

/**
 * ?CPU??so// w  w  w .  j av a2 s  .c om
 */
public int collectSoFiles() {
    HashMap<String, String> hashMap = HashFileHelper
            .parse(Constants.getHotfixPath(project, Constants.HOTFIX_SO_HASH));

    soFileMap = new HashMap<>();

    for (HashMap.Entry<String, String> entry : hashMap.entrySet()) {
        String soPath = project.getProjectDir().toString() + entry.getKey();
        File soFile = new File(soPath);

        if (!soFile.exists())
            continue;

        String archName = soFile.getParentFile().getName();
        if (onlyARM && !archName.equals("armeabi"))
            continue;

        String soHash = entry.getValue();

        try {
            String sha1Hex = DigestUtils.shaHex(Files.readAllBytes(soFile.toPath()));
            if (!sha1Hex.equals(soHash)) {

                if (soFileMap.containsKey(archName)) {
                    ArrayList<File> soFileList = soFileMap.get(archName);
                    soFileList.add(soFile);
                } else {
                    ArrayList<File> soFileList = new ArrayList<>();
                    soFileList.add(soFile);
                    soFileMap.put(archName, soFileList);
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    return soFileMap.size();
}

From source file:com.baeldung.file.FileOperationsManualTest.java

@Test
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
    String expectedData = "Hello World from fileTest.txt!!!";

    Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());

    byte[] fileBytes = Files.readAllBytes(path);
    String data = new String(fileBytes);

    assertEquals(expectedData, data.trim());
}