List of usage examples for java.io CharArrayReader CharArrayReader
public CharArrayReader(char buf[])
From source file:Main.java
public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String tmp = br.readLine();/*ww w.j a va2s. co m*/ int length = tmp.length(); char c[] = new char[length]; tmp.getChars(0, length, c, 0); CharArrayReader input1 = new CharArrayReader(c); int i; System.out.print("input1 is:"); while ((i = input1.read()) != -1) { System.out.print((char) i); } }
From source file:Main.java
public static void main(String args[]) throws IOException { CharArrayWriter outStream = new CharArrayWriter(); String s = "This is a test."; for (int i = 0; i < s.length(); ++i) outStream.write(s.charAt(i));// w w w . j a v a2 s . c om System.out.println("outstream: " + outStream); System.out.println("size: " + outStream.size()); CharArrayReader inStream; inStream = new CharArrayReader(outStream.toCharArray()); int ch = 0; StringBuffer sb = new StringBuffer(""); while ((ch = inStream.read()) != -1) sb.append((char) ch); s = sb.toString(); System.out.println(s.length() + " characters were read"); System.out.println("They are: " + s); }
From source file:com.twentyn.patentScorer.ScoreMerger.java
public static void main(String[] args) throws Exception { System.out.println("Starting up..."); System.out.flush();/*from w w w . ja v a 2s. c o 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
public static byte[] charArrayToByteArray(char[] buffer) { try {//from w w w. j a v a 2s . c om ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter out = new OutputStreamWriter(baos, ENCODING); Reader reader = new CharArrayReader(buffer); for (int ch; (ch = reader.read()) != -1;) { out.write(ch); } return baos.toByteArray(); } catch (Exception ex) { return null; } }
From source file:Main.java
public static Document loadString(String domContent) throws Exception { javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(false);/*w w w. ja v a2s . c o m*/ factory.setIgnoringElementContentWhitespace(false); factory.setValidating(false); factory.setCoalescing(false); DocumentBuilder builder = factory.newDocumentBuilder(); char[] chars = new char[domContent.length()]; domContent.getChars(0, domContent.length(), chars, 0); InputSource is = new InputSource(new CharArrayReader(chars)); return (builder.parse(is)); }
From source file:Main.java
/** * Create document from given array.//from w ww . j a v a 2 s. c o m * @param data * @return * @throws IllegalArgumentException */ public static Document createDocument(char[] data) throws IllegalArgumentException { Reader reader = new CharArrayReader(data); return createDocument(reader); }
From source file:Main.java
public static Document loadString(String paramString) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(false);/*www . j a va 2 s .co m*/ factory.setIgnoringElementContentWhitespace(false); factory.setValidating(false); factory.setCoalescing(false); DocumentBuilder builder = factory.newDocumentBuilder(); char[] arrayOfChar = new char[paramString.length()]; paramString.getChars(0, paramString.length(), arrayOfChar, 0); InputSource input = new InputSource(new CharArrayReader(arrayOfChar)); return builder.parse(input); }
From source file:net.sourceforge.pmd.cpd.AnyTokenizer.java
@Override public void tokenize(SourceCode sourceCode, Tokens tokenEntries) { StringBuilder sb = sourceCode.getCodeBuffer(); BufferedReader reader = new BufferedReader(new CharArrayReader(sb.toString().toCharArray())); try {//from w w w. j av a 2s .c o m int lineNumber = 1; String line = reader.readLine(); while (line != null) { StringTokenizer tokenizer = new StringTokenizer(line, TOKENS, true); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (!" ".equals(token) && !"\t".equals(token)) { tokenEntries.add(new TokenEntry(token, sourceCode.getFileName(), lineNumber)); } } // advance iteration variables line = reader.readLine(); lineNumber++; } } catch (IOException ignored) { ignored.printStackTrace(); } finally { IOUtils.closeQuietly(reader); tokenEntries.add(TokenEntry.getEOF()); } }
From source file:Main.java
/** * Filters an XML document./*ww w . ja v a 2 s . co m*/ * * @param source the input source for the XML document * @param filter the filter * * @return an input source for the resulting document * * @throws Exception */ public static InputSource filterXml(InputSource source, XMLFilter filter) throws Exception { // Create filter, which uses a "real" XMLReader but also removes the // attributes XMLReader reader = XMLReaderFactory.createXMLReader(); filter.setParent(reader); // Create a Transformer TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); // Transform the source tree, applying the filter, and store the result // tree in a character array CharArrayWriter writer = new CharArrayWriter(); t.transform(new SAXSource(filter, source), new StreamResult(writer)); // Return a new InputSource using the result tree return new InputSource(new CharArrayReader(writer.toCharArray())); }
From source file:com.codebutler.rsp.Util.java
public static Document parseXml(String xml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Reader reader = new CharArrayReader(xml.toCharArray()); return builder.parse(new org.xml.sax.InputSource(reader)); }