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:Test.java

public static void main(String[] args) throws IOException {
    Path path = Paths.get("/users.txt");
    byte[] contents = Files.readAllBytes(path);

    for (byte b : contents) {
        System.out.print((char) b);
    }//from  w  w  w.j  a v  a2  s .c  om

}

From source file:Main.java

public static void main(String[] args) {

    Path wiki_path = Paths.get("C:/tutorial/wiki", "wiki.txt");

    try {/*from   w  ww. j  a v  a  2 s .  c  o m*/
        byte[] wikiArray = Files.readAllBytes(wiki_path);

        String wikiString = new String(wikiArray, "ISO-8859-1");
        System.out.println(wikiString);
    } catch (IOException e) {
        System.out.println(e);
    }

}

From source file:Main.java

public static void main(String[] args) throws IOException {
    Path path = Paths.get("/users.txt");
    byte[] contents = Files.readAllBytes(path);

    Path newPath = Paths.get("/newUsers.txt");
    byte[] newContents = "aaa".getBytes();
    Files.write(newPath, contents, StandardOpenOption.CREATE);
    Files.write(newPath, newContents, StandardOpenOption.APPEND);
}

From source file:Main.java

public static void main(String[] args) throws IOException {
    Path path = Paths.get("/users.txt");
    byte[] contents = Files.readAllBytes(path);

    Path newPath = Paths.get("/newUsers.txt");

    Files.write(newPath, contents, StandardOpenOption.CREATE);

}

From source file:com.stackoverflow.so32806530.App.java

/**
 * Program EP./*www .ja  v  a 2 s  .c  om*/
 * @param args CLI args
 *
 * @throws URISyntaxException
 * @throws IOException
 */
public static void main(final String[] args) throws URISyntaxException, IOException {
    // ---------- Read response.xml -----
    final String xml = new String(
            Files.readAllBytes(Paths.get(App.class.getClassLoader().getResource("response.xml").toURI())),
            Charset.forName("UTF-8"));

    // ---------- starts fake API server -----
    final WireMockServer wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(8089));
    wireMockServer.stubFor(get(urlMatching("/v2/discovery/events.*")).willReturn(
            aResponse().withHeader("Content-type", "application/xml").withStatus(200).withBody(xml)));
    wireMockServer.start();
    // ---------------------------------------

    try {
        final String name = "foo";
        final String APIKEY = "MYAPI";
        final String URL = "http://localhost:8089/v2/discovery/events?apikey=" + APIKEY;
        final String readyUrl = URL + "&what=" + name;
        final RestTemplate restTemplate = new RestTemplate();
        final EventsResponse eventResponse = restTemplate.getForObject(readyUrl, EventsResponse.class);

        log.info("Seatwave: {}", eventResponse.getEvents().size());

        for (final Event event : eventResponse.getEvents()) {
            log.info("EventID: {}", event.getId());
        }
    } catch (final Exception ex) {
        log.error("Something went wrong", ex);
    }

    // ---------- stops fake API server ------
    wireMockServer.stop();
    // ---------------------------------------
}

From source file:DataCrawler.OpenAIRE.XMLGenerator.java

public static void main(String[] args) {
    String text = "";

    try {/*from w  w  w . jav a2  s .c o m*/
        if (args.length < 4) {
            System.out.println("<command> template_file csv_file output_dir log_file [start_id]");
        }

        // InputStream fis = new FileInputStream("E:/Downloads/result-r-00000");
        InputStream fis = new FileInputStream(args[1]);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));

        // String content = new String(Files.readAllBytes(Paths.get("publications_template.xml")));
        String content = new String(Files.readAllBytes(Paths.get(args[0])));
        Document doc = Jsoup.parse(content, "UTF-8", Parser.xmlParser());
        // String outputDirectory = "G:/";
        String outputDirectory = args[2];
        // PrintWriter logWriter = new PrintWriter(new FileOutputStream("publication.log",false));
        PrintWriter logWriter = new PrintWriter(new FileOutputStream(args[3], false));
        Element objectId = null, title = null, publisher = null, dateofacceptance = null, bestlicense = null,
                resulttype = null, originalId = null, originalId2 = null;
        boolean start = true;
        // String startID = "dedup_wf_001::207a098867b64f3b5af505fa3aeecd24";
        String startID = "";
        if (args.length >= 5) {
            start = false;
            startID = args[4];
        }
        String previousText = "";
        while ((text = br.readLine()) != null) {
            /*  For publications:
                0. dri:objIdentifier context
               9. title context
               12. publisher context
               18. dateofacceptance
               19. bestlicense @classname
               21. resulttype  @classname
               26. originalId context  
               (Notice that the prefix is null and will use space to separate two different "originalId")
            */

            if (!previousText.isEmpty()) {
                text = previousText + text;
                start = true;
                previousText = "";
            }

            String[] items = text.split("!");
            for (int i = 0; i < items.length; ++i) {
                items[i] = StringUtils.strip(items[i], "#");
            }
            if (objectId == null)
                objectId = doc.getElementsByTag("dri:objIdentifier").first();
            objectId.text(items[0]);

            if (!start && items[0].equals(startID)) {
                start = true;
            }

            if (title == null)
                title = doc.getElementsByTag("title").first();
            title.text(items[9]);

            if (publisher == null)
                publisher = doc.getElementsByTag("publisher").first();

            if (items.length < 12) {
                previousText = text;
                continue;
            }
            publisher.text(items[12]);

            if (dateofacceptance == null)
                dateofacceptance = doc.getElementsByTag("dateofacceptance").first();
            dateofacceptance.text(items[18]);

            if (bestlicense == null)
                bestlicense = doc.getElementsByTag("bestlicense").first();
            bestlicense.attr("classname", items[19]);

            if (resulttype == null)
                resulttype = doc.getElementsByTag("resulttype").first();
            resulttype.attr("classname", items[21]);

            if (originalId == null || originalId2 == null) {
                Elements elements = doc.getElementsByTag("originalId");
                String[] context = items[26].split(" ");
                if (elements.size() > 0) {
                    if (elements.size() >= 1) {
                        originalId = elements.get(0);
                        if (context.length >= 1) {
                            int indexOfnull = context[0].trim().indexOf("null");
                            String value = "";
                            if (indexOfnull != -1) {
                                if (context[0].trim().length() >= (indexOfnull + 5))
                                    value = context[0].trim().substring(indexOfnull + 5);

                            } else {
                                value = context[0].trim();
                            }
                            originalId.text(value);
                        }
                    }
                    if (elements.size() >= 2) {
                        originalId2 = elements.get(1);
                        if (context.length >= 2) {
                            int indexOfnull = context[1].trim().indexOf("null");
                            String value = "";
                            if (indexOfnull != -1) {
                                if (context[1].trim().length() >= (indexOfnull + 5))
                                    value = context[1].trim().substring(indexOfnull + 5);

                            } else {
                                value = context[1].trim();
                            }
                            originalId2.text(value);
                        }
                    }
                }
            } else {
                String[] context = items[26].split(" ");
                if (context.length >= 1) {
                    int indexOfnull = context[0].trim().indexOf("null");
                    String value = "";
                    if (indexOfnull != -1) {
                        if (context[0].trim().length() >= (indexOfnull + 5))
                            value = context[0].trim().substring(indexOfnull + 5);

                    } else {
                        value = context[0].trim();
                    }
                    originalId.text(value);
                }
                if (context.length >= 2) {
                    int indexOfnull = context[1].trim().indexOf("null");
                    String value = "";
                    if (indexOfnull != -1) {
                        if (context[1].trim().length() >= (indexOfnull + 5))
                            value = context[1].trim().substring(indexOfnull + 5);

                    } else {
                        value = context[1].trim();
                    }
                    originalId2.text(value);
                }
            }
            if (start) {
                String filePath = outputDirectory + items[0].replace(":", "#") + ".xml";
                PrintWriter writer = new PrintWriter(new FileOutputStream(filePath, false));
                logWriter.write(filePath + " > Start" + System.lineSeparator());
                writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + System.lineSeparator());
                writer.write(doc.getElementsByTag("response").first().toString());
                writer.close();
                logWriter.write(filePath + " > OK" + System.lineSeparator());
                logWriter.flush();
            }

        }
        logWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:test.jackson.JacksonNsgiRegister.java

public static void main(String[] args) throws IOException {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    String ngsiRcr = new String(Files.readAllBytes(Paths.get(NGSI_FILE)));

    RegisterContextRequest rcr = objectMapper.readValue(ngsiRcr, RegisterContextRequest.class);

    System.out.println(objectMapper.writeValueAsString(rcr));

    LinkedHashMap association = (LinkedHashMap) rcr.getContextRegistration().get(0).getContextMetadata().get(0)
            .getValue();/*w  ww  .  j  a  v a2 s .com*/
    Association assocObject = objectMapper.convertValue(association, Association.class);
    System.out.println(assocObject.getAttributeAssociation().get(0).getSourceAttribute());

    rcr.getContextRegistration().get(0).getContextRegistrationAttribute().get(1).getContextMetadata().get(0);

    //        System.out.println(rcr.getContextRegistration().get(0).getContextMetadata().get(0).getValue().getClass().getCanonicalName());

    //        String assocJson = objectMapper.writeValueAsString(association);
    //        Value assocObject =  objectMapper.readValue(objectMapper.writeValueAsString(association), Value.class);
    //        System.out.println(association.values().toString());
    //        System.out.println(assocJson);

}

From source file:net.dv8tion.jda.player.Bot.java

public static void main(String[] args) {
    try {/*from  w  w w  . ja v  a2s . c  om*/
        JSONObject obj = new JSONObject(new String(Files.readAllBytes(Paths.get("Config.json"))));
        JDA api = new JDABuilder().setBotToken(obj.getString("botToken")).addListener(new Bot())
                .buildBlocking();

    } catch (IllegalArgumentException e) {
        System.out.println("The config was not populated. Please provide a token.");
    } catch (LoginException e) {
        System.out.println("The provided botToken was incorrect. Please provide valid details.");
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        System.err.println(
                "Encountered a JSON error. Most likely caused due to an outdated or ill-formated config.\n"
                        + "Please delete the config so that it can be regenerated. JSON Error:\n");
        e.printStackTrace();
    } catch (IOException e) {
        JSONObject obj = new JSONObject();
        obj.put("botToken", "");
        try {
            Files.write(Paths.get("Config.json"), obj.toString(4).getBytes());
            System.out.println("No config file was found. Config.json has been generated, please populate it!");
        } catch (IOException e1) {
            System.out.println("No config file was found and we failed to generate one.");
            e1.printStackTrace();
        }
    }
}

From source file:com.kotcrab.vis.editor.CrashReporter.java

public static void main(String[] args) throws IOException {
    if (args.length != 2) {
        System.out.println("Invalid args, exiting.");
        System.exit(0);/*from  w w  w  . j ava2s  . co  m*/
    }

    restartCommand = args[0].replace("%", "\"");
    reportFile = new File(args[1]);
    if (reportFile.exists() == false) {
        System.out.println("Report file does not exist: " + args[1]);
        System.exit(0);
    }

    report = new String(Files.readAllBytes(reportFile.toPath()));

    launch(args);
}

From source file:test.jackson.JacksonNsgiDiscover.java

public static void main(String[] args) throws IOException {

    ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

    String ngsiRcr = new String(Files.readAllBytes(Paths.get(NGSI_FILE)));

    DiscoveryContextAvailabilityRequest dcar = objectMapper.readValue(ngsiRcr,
            DiscoveryContextAvailabilityRequest.class);

    //        System.out.println(objectMapper.writeValueAsString(dcar));
    System.out.println(dcar.getRestriction().getOperationScope().get(1).getScopeValue());

    LinkedHashMap shapeHMap = (LinkedHashMap) dcar.getRestriction().getOperationScope().get(1).getScopeValue();
    //        Association assocObject =  objectMapper.convertValue(shapeHMap, Association.class);
    //        System.out.println(assocObject.getAttributeAssociation().get(0).getSourceAttribute());

    Shape shape = objectMapper.convertValue(shapeHMap, Shape.class);
    System.out.println("Deserialized Class: " + shape.getClass().getSimpleName());
    System.out.println("VALUE: " + shape.getPolygon().getVertices().get(2).getLatitude());
    System.out.println("VALUE: " + shape.getCircle());
    if (!(shape.getCircle() == null))
        System.out.println("This is null");

    Polygon polygon = shape.getPolygon();
    int vertexSize = polygon.getVertices().size();
    Coordinate[] coords = new Coordinate[vertexSize];

    final ArrayList<Coordinate> points = new ArrayList<>();
    for (int i = 0; i < vertexSize; i++) {
        Vertex vertex = polygon.getVertices().get(i);
        points.add(new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude())));
        coords[i] = new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude()));
    }/*from   w  w w.  j a  v a  2 s.c  om*/
    points.add(new Coordinate(Double.valueOf(polygon.getVertices().get(0).getLatitude()),
            Double.valueOf(polygon.getVertices().get(0).getLongitude())));

    final GeometryFactory gf = new GeometryFactory();

    final Coordinate target = new Coordinate(49, -0.6);
    final Point point = gf.createPoint(target);

    Geometry shapeGm = gf.createPolygon(
            new LinearRing(new CoordinateArraySequence(points.toArray(new Coordinate[points.size()])), gf),
            null);
    //    Geometry shapeGm = gf.createPolygon(coords);    
    System.out.println(point.within(shapeGm));

    //        System.out.println(rcr.getContextRegistration().get(0).getContextMetadata().get(0).getValue().getClass().getCanonicalName());

    //        String assocJson = objectMapper.writeValueAsString(association);
    //        Value assocObject =  objectMapper.readValue(objectMapper.writeValueAsString(association), Value.class);
    //        System.out.println(association.values().toString());
    //        System.out.println(assocJson);

}