Example usage for java.nio CharBuffer array

List of usage examples for java.nio CharBuffer array

Introduction

In this page you can find the example usage for java.nio CharBuffer array.

Prototype

public final char[] array() 

Source Link

Document

Returns the char array which this buffer is based on, if there is one.

Usage

From source file:Main.java

public static void main(String[] args) {
    CharBuffer cb1 = CharBuffer.allocate(50);
    cb1.append("java2s.com");
    cb1.rewind();//from  w  w  w  .j a va  2  s. c  o  m

    System.out.println(cb1.arrayOffset());
    System.out.println(Arrays.toString(cb1.array()));

}

From source file:Main.java

public static void main(String[] args) {
    CharBuffer cb1 = CharBuffer.allocate(50);
    cb1.append("java2s.com");
    cb1.rewind();//from  w ww.  j a va 2s .  co m

    System.out.println(cb1.charAt(2));
    System.out.println(Arrays.toString(cb1.array()));

    CharBuffer cb2 = cb1.slice();
    System.out.println(Arrays.toString(cb2.array()));

}

From source file:Main.java

public static void main(String[] args) {
    CharBuffer cb1 = CharBuffer.allocate(50);
    cb1.append("java2s.com");
    cb1.rewind();/*from  w  w  w. ja v a2 s .  com*/

    System.out.println(cb1.charAt(2));
    System.out.println(Arrays.toString(cb1.array()));

    CharBuffer cb2 = cb1.compact();
    System.out.println(Arrays.toString(cb2.array()));

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    CharBuffer cb = CharBuffer.allocate(100);

    cb.put("This is a test String");

    cb.flip();// ww w . j  a  v  a 2s .  c  o  m

    System.out.println("hasArray() = " + cb.hasArray());

    char[] carray = cb.array();

    System.out.print("array=");

    for (int i = 0; i < carray.length; i++) {
        System.out.print(carray[i]);
    }

}

From source file:MainClass.java

public static void main(String[] argv) throws Exception {
    CharBuffer cb = CharBuffer.allocate(100);

    cb.put("This is a test String");

    cb.flip();//from  w w w.ja  v a 2s.  com

    System.out.println("hasArray() = " + cb.hasArray());

    char[] carray = cb.array();

    System.out.print("array=");

    for (int i = 0; i < carray.length; i++) {
        System.out.print(carray[i]);
    }

    System.out.println("");
    System.out.flush();
}

From source file:Main.java

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

    String s = "from java2s.com";

    StringReader sr = new StringReader(s);

    // create new buffered reader
    BufferedReader br = new BufferedReader(sr);

    // Destination source is created
    CharBuffer target = CharBuffer.allocate(s.length());

    // ready is invoked to test if character stream is ready
    if (br.ready()) {
        br.read(target);//from w w  w  .  j a  va  2 s  . c  o  m
    }
    System.out.print(target.array());

}

From source file:com.twentyn.patentScorer.ScoreMerger.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();/*  ww  w.  j a v  a  2s. co  m*/
    Options opts = new Options();
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());

    opts.addOption(Option.builder("r").longOpt("results").required().hasArg()
            .desc("A directory of search results to read").build());
    opts.addOption(Option.builder("s").longOpt("scores").required().hasArg()
            .desc("A directory of patent classification scores to read").build());
    opts.addOption(Option.builder("o").longOpt("output").required().hasArg()
            .desc("The output file where results will be written.").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }
    File scoresDirectory = new File(cmdLine.getOptionValue("scores"));
    if (cmdLine.getOptionValue("scores") == null || !scoresDirectory.isDirectory()) {
        LOGGER.error("Not a directory of score files: " + cmdLine.getOptionValue("scores"));
    }

    File resultsDirectory = new File(cmdLine.getOptionValue("results"));
    if (cmdLine.getOptionValue("results") == null || !resultsDirectory.isDirectory()) {
        LOGGER.error("Not a directory of results files: " + cmdLine.getOptionValue("results"));
    }

    FileWriter outputWriter = new FileWriter(cmdLine.getOptionValue("output"));

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

    FilenameFilter jsonFilter = new FilenameFilter() {
        public final Pattern JSON_PATTERN = Pattern.compile("\\.json$");

        public boolean accept(File dir, String name) {
            return JSON_PATTERN.matcher(name).find();
        }
    };

    Map<String, PatentScorer.ClassificationResult> scores = new HashMap<>();
    LOGGER.info("Reading scores from directory at " + scoresDirectory.getAbsolutePath());
    for (File scoreFile : scoresDirectory.listFiles(jsonFilter)) {
        BufferedReader reader = new BufferedReader(new FileReader(scoreFile));
        int count = 0;
        String line;
        while ((line = reader.readLine()) != null) {
            PatentScorer.ClassificationResult res = objectMapper.readValue(line,
                    PatentScorer.ClassificationResult.class);
            scores.put(res.docId, res);
            count++;
        }
        LOGGER.info("Read " + count + " scores from " + scoreFile.getAbsolutePath());
    }

    Map<String, List<DocumentSearch.SearchResult>> synonymsToResults = new HashMap<>();
    Map<String, List<DocumentSearch.SearchResult>> inchisToResults = new HashMap<>();
    LOGGER.info("Reading results from directory at " + resultsDirectory);
    // With help from http://stackoverflow.com/questions/6846244/jackson-and-generic-type-reference.
    JavaType resultsType = objectMapper.getTypeFactory().constructCollectionType(List.class,
            DocumentSearch.SearchResult.class);

    List<File> resultsFiles = Arrays.asList(resultsDirectory.listFiles(jsonFilter));
    Collections.sort(resultsFiles, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    for (File resultsFile : resultsFiles) {
        BufferedReader reader = new BufferedReader(new FileReader(resultsFile));
        CharBuffer buffer = CharBuffer.allocate(Long.valueOf(resultsFile.length()).intValue());
        int bytesRead = reader.read(buffer);
        LOGGER.info("Read " + bytesRead + " bytes from " + resultsFile.getName() + " (length is "
                + resultsFile.length() + ")");
        List<DocumentSearch.SearchResult> results = objectMapper.readValue(new CharArrayReader(buffer.array()),
                resultsType);

        LOGGER.info("Read " + results.size() + " results from " + resultsFile.getAbsolutePath());

        int count = 0;
        for (DocumentSearch.SearchResult sres : results) {
            for (DocumentSearch.ResultDocument resDoc : sres.getResults()) {
                String docId = resDoc.getDocId();
                PatentScorer.ClassificationResult classificationResult = scores.get(docId);
                if (classificationResult == null) {
                    LOGGER.warn("No classification result found for " + docId);
                } else {
                    resDoc.setClassifierScore(classificationResult.getScore());
                }
            }
            if (!synonymsToResults.containsKey(sres.getSynonym())) {
                synonymsToResults.put(sres.getSynonym(), new ArrayList<DocumentSearch.SearchResult>());
            }
            synonymsToResults.get(sres.getSynonym()).add(sres);
            count++;
            if (count % 1000 == 0) {
                LOGGER.info("Processed " + count + " search result documents");
            }
        }
    }

    Comparator<DocumentSearch.ResultDocument> resultDocumentComparator = new Comparator<DocumentSearch.ResultDocument>() {
        @Override
        public int compare(DocumentSearch.ResultDocument o1, DocumentSearch.ResultDocument o2) {
            int cmp = o2.getClassifierScore().compareTo(o1.getClassifierScore());
            if (cmp != 0) {
                return cmp;
            }
            cmp = o2.getScore().compareTo(o1.getScore());
            return cmp;
        }
    };

    for (Map.Entry<String, List<DocumentSearch.SearchResult>> entry : synonymsToResults.entrySet()) {
        DocumentSearch.SearchResult newSearchRes = null;
        // Merge all result documents into a single search result.
        for (DocumentSearch.SearchResult sr : entry.getValue()) {
            if (newSearchRes == null) {
                newSearchRes = sr;
            } else {
                newSearchRes.getResults().addAll(sr.getResults());
            }
        }
        if (newSearchRes == null || newSearchRes.getResults() == null) {
            LOGGER.error("Search results for " + entry.getKey() + " are null.");
            continue;
        }
        Collections.sort(newSearchRes.getResults(), resultDocumentComparator);
        if (!inchisToResults.containsKey(newSearchRes.getInchi())) {
            inchisToResults.put(newSearchRes.getInchi(), new ArrayList<DocumentSearch.SearchResult>());
        }
        inchisToResults.get(newSearchRes.getInchi()).add(newSearchRes);
    }

    List<String> sortedKeys = new ArrayList<String>(inchisToResults.keySet());
    Collections.sort(sortedKeys);
    List<GroupedInchiResults> orderedResults = new ArrayList<>(sortedKeys.size());
    Comparator<DocumentSearch.SearchResult> synonymSorter = new Comparator<DocumentSearch.SearchResult>() {
        @Override
        public int compare(DocumentSearch.SearchResult o1, DocumentSearch.SearchResult o2) {
            return o1.getSynonym().compareTo(o2.getSynonym());
        }
    };
    for (String inchi : sortedKeys) {
        List<DocumentSearch.SearchResult> res = inchisToResults.get(inchi);
        Collections.sort(res, synonymSorter);
        orderedResults.add(new GroupedInchiResults(inchi, res));
    }

    objectMapper.writerWithView(Object.class).writeValue(outputWriter, orderedResults);
    outputWriter.close();
}

From source file:Main.java

/**
 * bytes tp chars/*from   w  w w.  ja  va  2s . co  m*/
 * 
 * @param bytes
 * @return
 */
public static char[] getChars(byte[] bytes) {
    Charset cs = Charset.forName("UTF-8");
    ByteBuffer bb = ByteBuffer.allocate(bytes.length);
    bb.put(bytes);
    bb.flip();
    CharBuffer cb = cs.decode(bb);
    return cb.array();
}

From source file:Main.java

private static String decode(Charset charset, byte[] b) {
    if (b == null) {
        return null;
    }/*ww w .  j  a  v  a2  s .  c om*/
    final CharBuffer cb = charset.decode(ByteBuffer.wrap(b));
    return new String(cb.array(), 0, cb.length());
}

From source file:ChannelToWriter.java

/**
 * Read bytes from the specified channel, decode them using the specified
 * Charset, and write the resulting characters to the specified writer
 *//*from   w  w w  . j  a  v a2  s.c  o m*/
public static void copy(ReadableByteChannel channel, Writer writer, Charset charset) throws IOException {
    // Get and configure the CharsetDecoder we'll use
    CharsetDecoder decoder = charset.newDecoder();
    decoder.onMalformedInput(CodingErrorAction.IGNORE);
    decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);

    // Get the buffers we'll use, and the backing array for the CharBuffer.
    ByteBuffer bytes = ByteBuffer.allocateDirect(2 * 1024);
    CharBuffer chars = CharBuffer.allocate(2 * 1024);
    char[] array = chars.array();

    while (channel.read(bytes) != -1) { // Read from channel until EOF
        bytes.flip(); // Switch to drain mode for decoding
        // Decode the byte buffer into the char buffer.
        // Pass false to indicate that we're not done.
        decoder.decode(bytes, chars, false);

        // Put the char buffer into drain mode, and write its contents
        // to the Writer, reading them from the backing array.
        chars.flip();
        writer.write(array, chars.position(), chars.remaining());

        // Discard all bytes we decoded, and put the byte buffer back into
        // fill mode. Since all characters were output, clear that buffer.
        bytes.compact(); // Discard decoded bytes
        chars.clear(); // Clear the character buffer
    }

    // At this point there may still be some bytes in the buffer to decode
    // So put the buffer into drain mode call decode() a final time, and
    // finish with a flush().
    bytes.flip();
    decoder.decode(bytes, chars, true); // True means final call
    decoder.flush(chars); // Flush any buffered chars
    // Write these final chars (if any) to the writer.
    chars.flip();
    writer.write(array, chars.position(), chars.remaining());
    writer.flush();
}