Example usage for java.lang String String

List of usage examples for java.lang String String

Introduction

In this page you can find the example usage for java.lang String String.

Prototype

String(byte[] value, byte coder) 

Source Link

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    byte buff[] = new byte[1024];
    InetAddress addr = InetAddress.getByName("www.java2s.com");
    Socket s = new Socket(addr, 80);

    OutputStream output = s.getOutputStream();
    InputStream input = s.getInputStream();
    String GetCmd = "GET /index.html HTTP/1.0\r\n\r\n";
    GetCmd.getBytes(0, GetCmd.length(), buff, 0);
    output.write(buff);/*from   w  ww.j  a  v a  2  s  .  c o  m*/
    input.read(buff, 0, buff.length);
    System.out.println(new String(buff, 0));

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path path = Paths.get("test.txt");

    try (AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, StandardOpenOption.READ)) {
        int fileSize = (int) afc.size();
        ByteBuffer dataBuffer = ByteBuffer.allocate(fileSize);

        Future<Integer> result = afc.read(dataBuffer, 0);
        int readBytes = result.get();

        System.out.format("%s bytes read   from  %s%n", readBytes, path);
        System.out.format("Read data is:%n");

        byte[] byteData = dataBuffer.array();
        Charset cs = Charset.forName("UTF-8");
        String data = new String(byteData, cs);

        System.out.println(data);
    } catch (IOException ex) {
        ex.printStackTrace();/*from   ww w . ja va  2 s . c om*/
    }
}

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

/**
 * Program EP./*w ww .  j a v a 2  s.  co  m*/
 * @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:com.doctor.base64.CommonsCodecBase64.java

public static void main(String[] args) {
    String plainText = "Base64??"
            + "??ASCII???"
            + "????Base64";

    // ??/*from w  w w.  j a  va 2  s. c om*/
    String base64String = Base64.encodeBase64String(plainText.getBytes(StandardCharsets.UTF_8));
    System.out.println(base64String);

    String plainTxt = new String(Base64.decodeBase64(base64String), StandardCharsets.UTF_8);
    Preconditions.checkArgument(plainTxt.equals(plainText));

    // ??
    base64String = new String(Base64.encodeBase64Chunked(plainText.getBytes(StandardCharsets.UTF_8)),
            StandardCharsets.UTF_8);
    plainTxt = new String(Base64.decodeBase64(base64String), StandardCharsets.UTF_8);
    Preconditions.checkArgument(plainTxt.equals(plainText));

}

From source file:SenBench.java

public static void main(String[] args) {
    try {//from www . j  a v  a  2  s.  c om
        if (args.length == 0) {
            System.out.println("usage: java SenBench file [file ..]");
            System.exit(2);
        }

        StringTagger tagger = StringTagger.getInstance(Locale.JAPANESE);

        long processed = 0;
        long nbytes = 0;
        long nchars = 0;

        long start = System.currentTimeMillis();
        for (int a = 0; a < args.length; a++) {
            String text = "";
            try {
                RandomAccessFile raf = new RandomAccessFile(args[a], "r");
                byte[] buf = new byte[(int) raf.length()];
                raf.readFully(buf);
                raf.close();
                text = new String(buf, encoding);
                nbytes += buf.length;
                nchars += text.length();
            } catch (IOException ioe) {
                log.error(ioe);
                continue;
            }

            long s_start = System.currentTimeMillis();
            for (int c = 0; c < repeat; c++)
                doWork(tagger, text);
            long s_end = System.currentTimeMillis();
            processed += (s_end - s_start);
        }
        long end = System.currentTimeMillis();
        System.out.println("number of files: " + args.length);
        System.out.println("number of repeat: " + repeat);
        System.out.println("number of bytes: " + nbytes);
        System.out.println("number of chars: " + nchars);
        System.out.println("total time elapsed: " + (end - start) + " msec.");
        System.out.println("analysis time: " + (processed) + " msec.");
    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:cn.xyz.lcg.rocketmq.quickstart.PullConsumer.java

public static void main(String[] args) throws MQClientException {
    DefaultMQPullConsumer consumer = new DefaultMQPullConsumer("simplePullConsumer");

    consumer.setNamesrvAddr("centOS1:9876");

    consumer.start();/*from   ww w .  j ava 2 s. co m*/

    Set<MessageQueue> mqs = consumer.fetchSubscribeMessageQueues("simpleTest");
    for (MessageQueue mq : mqs) {
        // System.out.println("Consume from the queue: " + mq);
        SINGLE_MQ: while (true) {
            try {
                PullResult pullResult = consumer.pullBlockIfNotFound(mq, null, getMessageQueueOffset(mq), 32);
                // System.out.println(pullResult);
                if (CollectionUtils.isNotEmpty(pullResult.getMsgFoundList())) {
                    for (MessageExt msg : pullResult.getMsgFoundList()) {
                        System.out.println(
                                Thread.currentThread().getName() + " " + new String(msg.getBody(), "UTF-8"));
                    }
                }
                putMessageQueueOffset(mq, pullResult.getNextBeginOffset());
                switch (pullResult.getPullStatus()) {
                case FOUND:
                    break;
                case NO_MATCHED_MSG:
                    break;
                case NO_NEW_MSG:
                    break SINGLE_MQ;
                case OFFSET_ILLEGAL:
                    break;
                default:
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    consumer.shutdown();
}

From source file:cn.xyz.lcg.rocketmq.cluster.PullConsumer2mNoSlave.java

public static void main(String[] args) throws MQClientException {
    DefaultMQPullConsumer consumer = new DefaultMQPullConsumer("2mNoSlaveConsumer");

    consumer.setNamesrvAddr("centOS1:9876;cenetOS2:9876");

    consumer.start();//from ww  w  .ja v a2s .  c  om

    Set<MessageQueue> mqs = consumer.fetchSubscribeMessageQueues("2mNoSlaveTest");
    for (MessageQueue mq : mqs) {
        // System.out.println("Consume from the queue: " + mq);
        SINGLE_MQ: while (true) {
            try {
                PullResult pullResult = consumer.pullBlockIfNotFound(mq, null, getMessageQueueOffset(mq), 32);
                // System.out.println(pullResult);
                if (CollectionUtils.isNotEmpty(pullResult.getMsgFoundList())) {
                    for (MessageExt msg : pullResult.getMsgFoundList()) {
                        System.out.println(
                                Thread.currentThread().getName() + " " + new String(msg.getBody(), "UTF-8"));
                    }
                }
                putMessageQueueOffset(mq, pullResult.getNextBeginOffset());
                switch (pullResult.getPullStatus()) {
                case FOUND:
                    break;
                case NO_MATCHED_MSG:
                    break;
                case NO_NEW_MSG:
                    break SINGLE_MQ;
                case OFFSET_ILLEGAL:
                    break;
                default:
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    consumer.shutdown();
}

From source file:com.reversemind.glia.test.go3.java

public static void main(String... args) throws Exception {

    System.setProperty("http.proxyHost", "10.105.0.217");
    System.setProperty("http.proxyPort", "3128");

    System.setProperty("https.proxyHost", "10.105.0.217");
    System.setProperty("https.proxyPort", "3128");

    HttpHost proxy = new HttpHost("10.105.0.217", 3128);
    DefaultHttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    HttpGet request = new HttpGet(
            "https://twitter.com/i/profiles/show/splix/timeline/with_replies?include_available_features=1&include_entities=1&max_id=285605679744569344");
    HttpResponse response = client.execute(request);

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

    String sl = "";
    String line = "";
    while ((line = rd.readLine()) != null) {
        LOG.debug(line);/*from ww  w  .  j  a v  a2  s.co  m*/
        sl += line;
    }

    sl = new String(sl.getBytes(), "UTF-8");
    String sss = sl.replaceAll("\\{1,}", "\\").replaceAll("\\\"", "'").replaceAll("\\&quot;", "'")
            .replaceAll("&gt;", ">").replaceAll("&lt;", "<").replaceAll("&amp;", "&").replaceAll("&apos;", "'")
            .replaceAll("\u003c", "<").replaceAll("\u003e", ">").replaceAll("\n", " ").replaceAll("\\/", "/")
            .replaceAll("\\'", "'");

    String sss2 = sss.replaceAll("\\'", "'");
    LOG.debug(sss);

    save("/opt/_del/go_sl.txt", sl);
    save("/opt/_del/go_sss.txt", sss);
    save("/opt/_del/go_line.txt", line);
    save("/opt/_del/go_sss2.txt", sss2);

    LOG.debug("\n\n\n\n\n");
    LOG.debug(sss);
    LOG.debug("\n\n\n\n\n");
    LOG.debug(URLDecoder.decode(sl, "UTF-8"));
    LOG.debug(URLDecoder.decode("\u0438\u043d\u043e\u0433\u0434\u0430", "UTF-8"));

    LOG.debug(URLDecoder.decode("\n            \u003c/span\u003e\n            \u003cb\u003e\n ", "UTF-8"));

}

From source file:cn.xyz.lcg.rocketmq.broadcasting.Consumer.java

public static void main(String[] args) throws InterruptedException, MQClientException {
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("broadcastingConsumer");

    consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

    consumer.setMessageModel(MessageModel.BROADCASTING);

    consumer.setNamesrvAddr("centOS1:9876");

    consumer.subscribe("broadcastingTest", "*");

    consumer.registerMessageListener(new MessageListenerConcurrently() {

        @Override//from   w w w .j a v a2s. c  o m
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                ConsumeConcurrentlyContext context) {
            // System.out.println(Thread.currentThread().getName() + "
            // Receive New Messages: " + msgs);
            if (CollectionUtils.isNotEmpty(msgs)) {
                for (MessageExt msg : msgs) {
                    try {
                        System.out.println(
                                Thread.currentThread().getName() + " " + new String(msg.getBody(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        // ignore
                    }

                }
            }

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.println("Broadcast Consumer Started.");
}

From source file:cn.xyz.lcg.rocketmq.filter.Consumer.java

public static void main(String[] args) throws InterruptedException, MQClientException, IOException {
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("filterConsumer");

    consumer.setNamesrvAddr("centOS1:9876");

    // consumer.setConsumeThreadMin(1);
    // consumer.setConsumeThreadMax(1);

    InputStream is = Consumer.class.getResourceAsStream("/cn/xyz/lcg/rocketmq/filter/MessageFilterImpl.java");

    String filterCode = IOUtils.toString(is);

    consumer.subscribe("filterTest", "cn.xyz.lcg.rocketmq.filter.MessageFilterImpl", filterCode);

    // consumer.subscribe("TopicFilter7", "*");

    consumer.registerMessageListener(new MessageListenerConcurrently() {

        @Override//from   ww  w. jav a 2s  .  c o m
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                ConsumeConcurrentlyContext context) {
            if (CollectionUtils.isNotEmpty(msgs)) {
                for (MessageExt msg : msgs) {
                    try {
                        System.out.println(
                                Thread.currentThread().getName() + " " + new String(msg.getBody(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        // ignore
                    }

                }
            }
            // System.out.println(Thread.currentThread().getName() + "
            // Receive New Messages: " + msgs);
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.println("Consumer Started.");
}