Example usage for org.apache.commons.io IOUtils toString

List of usage examples for org.apache.commons.io IOUtils toString

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils toString.

Prototype

public static String toString(byte[] input) throws IOException 

Source Link

Document

Get the contents of a byte[] as a String using the default character encoding of the platform.

Usage

From source file:Resource.java

/**
 * @param args//from w w w.j  a  v a2  s  .c  om
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = cl.getResourceAsStream("com/sap/ca/aspose/license/Aspose.Total.Java.lic");
    //InputStream is = cl.getResourceAsStream("com/sap/ca/aspose/license/a.txt");
    if (is == null) {
        System.err.println("Error is is null");
        System.exit(1);

    }
    String s;
    try {
        s = IOUtils.toString(is);
        System.out.println(s);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:gsonTests.jsonTojava.ParseTreeExample6.java

public static void main(String[] args) throws MalformedURLException, IOException {
    String url = "http://freemusicarchive.org/api/get/albums.json?api_key=60BLHNQCAOUFPIBZ&limit=5";
    String json = IOUtils.toString(new URL(url));
    JsonParser parser = new JsonParser();
    // The JsonElement is the root node. It can be an object, array, null or
    // java primitive.
    JsonElement element = parser.parse(json);
    // use the isxxx methods to find out the type of jsonelement. In our
    // example we know that the root object is the Albums object and
    // contains an array of dataset objects
    if (element.isJsonObject()) {
        JsonObject albums = element.getAsJsonObject();
        System.out.println(albums.get("title").getAsString());
        JsonArray datasets = albums.getAsJsonArray("dataset");
        for (int i = 0; i < datasets.size(); i++) {
            JsonObject dataset = datasets.get(i).getAsJsonObject();
            System.out.println(dataset.get("album_title").getAsString());
        }/*from w w w .  j av a 2s.c  o m*/
    }

}

From source file:devartisan.ConvertJSONToXML.java

public static void main(String[] args) throws Exception {
    String jsonData = "{'foo':'bar','coolness':2.0,'altitude':39000,'pilot':{'firstName':'Buzz','lastName':'Aldrin'},'mission':'apollo 11'}";

    InputStream is = ConvertJSONToXML.class.getResourceAsStream("sample-json.txt");

    if (is != null) {
        jsonData = IOUtils.toString(is);

    }/*  ww  w .  j  a  v a2  s.  co m*/

    XMLSerializer serializer = new XMLSerializer();
    JSON json = JSONSerializer.toJSON(jsonData);
    String xml = serializer.write(json);
    System.out.println(xml);
}

From source file:com.project.finalproject.Send.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    try {//  ww w.  ja v a 2  s  .  c om
        InputStream is = new FileInputStream("hr.json");
        String jsontxt = IOUtils.toString(is);
        JSONObject jsonObject = new JSONObject(jsontxt);
        JSONArray stream = jsonObject.getJSONArray("stream");
        for (int i = 0; i < stream.length(); i++) {
            String message = stream.getJSONObject(i).getString("value");
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
            System.out.println(" [x] Sent '" + message + "'");
            TimeUnit.SECONDS.sleep(1);
        }
    } catch (FileNotFoundException fe) {
        fe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    channel.close();
    connection.close();
}

From source file:bonapetit.ParseJson1.java

public static void main(String[] args) {
    String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
    /*// w w w .  j  a va  2  s  . c  o  m
     * {"title":"Free Music Archive - Genres","message":"","errors":[],"total" : "161","total_pages":81,"page":1,"limit":"2",
     * "dataset":
     * [{"genre_id": "1","genre_parent_id":"38","genre_title":"Avant-Garde" ,"genre_handle": "Avant-Garde","genre_color":"#006666"},
     * {"genre_id":"2","genre_parent_id" :null,"genre_title":"International","genre_handle":"International","genre_color":"#CC3300"}]}
     */
    try {
        String genreJson = IOUtils.toString(new URL(url));
        JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
        // get the title
        System.out.println(genreJsonObject.get("title"));
        // get the data
        JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
        // get the first genre
        JSONObject firstGenre = (JSONObject) genreArray.get(0);
        System.out.println(firstGenre.get("genre_title"));
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
}

From source file:de.topobyte.collections.util.gen.GenListToArray.java

public static void main(String[] args) throws IOException {
    InputStream input = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("listAsArray.template");
    String template = IOUtils.toString(input);

    for (PrimitiveType type : PrimitiveType.values()) {
        System.out.println(InstanceCreator.create(template, type));
    }/*from w  w  w. j  av a2  s . c o m*/
}

From source file:de.topobyte.collections.util.gen.GenCollectionToArray.java

public static void main(String[] args) throws IOException {
    InputStream input = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("collectionAsArray.template");
    String template = IOUtils.toString(input);

    for (PrimitiveType type : PrimitiveType.values()) {
        System.out.println(InstanceCreator.create(template, type));
    }/*from  w w  w .  j  a va2 s .c  o  m*/
}

From source file:goeurotest.GoEuroTest.java

/**
 * @param args the command line arguments
 *///  w  w  w.  j  a  v  a 2 s  .  c om
public static void main(String[] args) {

    Console console = System.console();

    if (args.length != 1) {
        if (console != null)
            console.writer().println("Usage: java -jar GoEuroTest.jar <CITY_NAME>");
        return;
    }

    URL url;

    try {
        url = new URL("http://api.goeuro.com/api/v2/position/suggest/en/" + args[0]);
    } catch (MalformedURLException ex) {
        if (console != null)
            console.writer().println("Malformed URL. Make sure the first parameter is the name of the city.");
        return;
    }

    String json;

    try {
        json = IOUtils.toString(url);
    } catch (IOException ex) {
        if (console != null)
            console.writer().println("Unable to contact the GoEuro API");
        return;
    }

    JsonParser parser = new JsonParser();

    try {
        JsonArray cities = parser.parse(json).getAsJsonArray();

        if (cities.size() == 0) {
            if (console != null)
                console.writer().println("No results found");
            return;
        }

        for (int i = 0; i < cities.size(); i++) {
            JsonObject city = cities.get(i).getAsJsonObject();
            String id = city.get("_id").getAsString();
            String name = city.get("name").getAsString();
            String type = city.get("type").getAsString();
            JsonObject geo_position = city.get("geo_position").getAsJsonObject();
            String latitude = geo_position.get("latitude").getAsString();
            String longitude = geo_position.get("longitude").getAsString();
            String entry = id + "," + name + "," + type + "," + latitude + "," + longitude;
            System.out.println(entry);

        }
    } catch (Exception e) {
        if (console != null)
            console.writer().println("Malformed API response.");
    }
}

From source file:de.mirkosertic.invertedindex.core.FullIndexRun.java

public static void main(String[] args) throws IOException {
    InvertedIndex theIndex = new InvertedIndex();
    UpdateIndexHandler theIndexHandler = new UpdateIndexHandler(theIndex);
    Tokenizer theTokenizer = new Tokenizer(new ToLowercaseTokenHandler(theIndexHandler));

    File theOrigin = new File("/home/sertic/ownCloud/Textcontent");
    for (File theFile : theOrigin.listFiles()) {
        System.out.println("Indexing " + theFile);
        String theFileContent = IOUtils.toString(new FileReader(theFile));
        theTokenizer.process(new Document(theFile.getName(), theFileContent));
    }/*from   w w  w  . j  a  v  a 2  s.co  m*/

    System.out.println(theIndex.getTokenCount() + " unique postings");
    System.out.println(theIndex.getDocumentCount() + " documents");

    theIndex.postings.entrySet().stream()
            .sorted((o1, o2) -> ((Integer) o1.getValue().getOccoursInDocuments().size())
                    .compareTo(o2.getValue().getOccoursInDocuments().size()))
            .forEach(t -> {
                System.out.println(t.getKey() + " -> " + t.getValue().getOccoursInDocuments().size());
            });

    System.out.println("Query");

    Result theResult = theIndex.query(new TokenSequenceQuery(new String[] { "introduction", "to", "aop" }));
    System.out.println(theResult.getSize());
    for (int i = 0; i < theResult.getSize(); i++) {
        System.out.println(theResult.getDoc(i).getName());

        System.out.println(theIndex.rebuildContentFor(theResult.getDoc(i)));
    }

    long theCount = 100000;
    long theStart = System.currentTimeMillis();
    for (int i = 0; i < theCount; i++) {
        theResult = theIndex.query(new TokenSequenceQuery(new String[] { "introduction", "to", "aop" }));
    }
    double theDuration = System.currentTimeMillis() - theStart;

    System.out.println(theCount + " Queries took " + theDuration + "ms");
    System.out.println(theDuration / theCount);

    while (true) {
        theResult = theIndex.query(new TokenSequenceQuery(new String[] { "introduction", "to", "aop" }));
    }
}

From source file:com.l2jserver.tool.conversor.itemtemplate.ItemTemplateConversor.java

public static void main(String[] args) throws IOException {
    template = IOUtils.toString(ItemTemplateConversor.class.getResourceAsStream("ItemTemplateBase.txt"));

    Collection<File> files = FileUtils.listFiles(
            new File("/home/rogiel/Documents/Eclipse/lineage2/L2J_DataPack_BETA/data/stats/items"),
            new String[] { "xml" }, false);

    for (final File file : files) {
        processFile(file.getAbsolutePath());
    }//from   w  w  w.ja va2 s  .c o  m
}