List of usage examples for java.nio CharBuffer allocate
public static CharBuffer allocate(int capacity)
From source file:fi.johannes.kata.ocr.utils.files.CFileOperations.java
public static void createChunksByRowsChars(String inputFile, String outputFolder, int bufferSize, int rows) throws FileNotFoundException, IOException { File f = new File(inputFile); String filename = f.getName(); BufferedReader bw = new BufferedReader(new FileReader(f)); CharBuffer buffer = CharBuffer.allocate(bufferSize); int j = 0;/*from www. j av a 2s . co m*/ for (int i = 0; i <= rows; i++) { String lineStr = bw.readLine(); if (lineStr != null) { char[] line = lineStr.toCharArray(); if (i == rows) { String outputfile = outputFolder + j + "-" + filename; writeChunk(buffer, outputfile); buffer.clear(); j++; i = 0; } buffer.put(line); buffer.put(System.getProperty("line.separator")); } else { break; } } }
From source file:de.alpharogroup.random.RandomExtensionsTest.java
/** * Test method for {@link RandomExtensions#randomChar(java.lang.String)} . *///w w w. j av a2 s. co m @Test public void testRandomChar() { final String string = Constants.LOWCASECHARS; for (int i = 0; i < 100; i++) { final char randomChar = RandomExtensions.randomChar(string); final CharBuffer charBuffer = CharBuffer.allocate(1); charBuffer.put(randomChar); this.result = string.contains(charBuffer); AssertJUnit.assertTrue("", this.result); } }
From source file:esg.node.components.monitoring.InfoResources.java
InfoResources(String filename, int buffSize_) { this.filename = filename; this.buffSize = buffSize_; System.out.println("InfoResource initializing for " + filename); try {// w w w. ja v a2 s. c o m File procFile = new File(filename); if (buffSize < 0) { buffSize = (int) procFile.length(); if (buffSize == 0) { buffSize = guestimateSize; } } raf = new RandomAccessFile(procFile, "r"); fc = raf.getChannel(); bb = ByteBuffer.allocateDirect(buffSize); Charset cs = Charset.forName("8859_1"); decoder = cs.newDecoder(); cb = CharBuffer.allocate(buffSize); System.out.println("Buffer Size is " + buffSize + " number of bytes"); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.cloudera.sqoop.io.TestLobFile.java
/** * Run a test where we read only a fraction of the first record, * but then read the second record completely. Verify that we * can re-align on a record boundary correctly. This test requires * at least 3 records.//from w ww . j a v a2s . c o m * @param p the path to the file to create. * @param firstLine the first line of the first reord * @param records All of the records to write to the file. */ private void runLineAndRecordTest(Path p, String firstLine, String... records) throws Exception { assertTrue("This test requires 3+ records", records.length > 2); writeClobFile(p, null, records); LobFile.Reader reader = LobFile.open(p, conf); // We should not yet be aligned. assertFalse(reader.isRecordAvailable()); assertTrue(reader.next()); // Now we should be. assertTrue(reader.isRecordAvailable()); // Read just one line from the record. Reader r = reader.readClobRecord(); BufferedReader br = new BufferedReader(r); String line = br.readLine(); assertEquals(firstLine, line); br.close(); r.close(); // We should no longer be aligned on a record start. assertFalse(reader.isRecordAvailable()); // We should now be able to get to record two. assertTrue(reader.next()); // This should be nicely aligned even if the first record was not // completely consumed by a client. r = reader.readClobRecord(); CharBuffer buf = CharBuffer.allocate(records[1].length()); r.read(buf); r.close(); char[] chars = buf.array(); String s = new String(chars); assertEquals(records[1], s); // Close the reader before we consume the entire file. reader.close(); assertFalse(reader.isRecordAvailable()); }
From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java
/** * Initialize UI model from a .jzml file * //from w ww . j a va 2s. com * @param zipTouchoscFilePath a .jzml file * * @return UI model */ public TouchOscApp loadAppFromTouchOscXML(String zipTouchoscFilePath) { // // Create a resource set. // ResourceSet resourceSet = new ResourceSetImpl(); IPath path = new Path(zipTouchoscFilePath); // // Register the default resource factory -- only needed for stand-alone! // resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX, new TouchoscResourceFactoryImpl()); resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE); resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE); List<String> touchoscFilePathList = new ArrayList<String>(); try { FileInputStream touchoscFile = new FileInputStream(zipTouchoscFilePath); ZipInputStream fileIS = new ZipInputStream(touchoscFile); ZipEntry zEntry = null; while ((zEntry = fileIS.getNextEntry()) != null) { if (zEntry.getName().endsWith(".xml")) { touchoscFilePathList.add(path.removeLastSegments(1) + "/_" + path.lastSegment()); } FileOutputStream os = new FileOutputStream(path.removeLastSegments(1) + "/_" + path.lastSegment()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os)); BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8"))); CharBuffer charBuffer = CharBuffer.allocate(65535); while (reader.read(charBuffer) != -1) charBuffer.append("</touchosc:TOP>\n"); charBuffer.flip(); String content = charBuffer.toString(); content = content.replace("<touchosc>", ""); content = content.replace("</touchosc>", ""); content = content.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", TOUCHOSC_XMLNS_HEADER); content = content.replace("numberX=", "number_x="); content = content.replace("numberY=", "number_y="); content = content.replace("invertedX=", "inverted_x="); content = content.replace("invertedY=", "inverted_y="); content = content.replace("localOff=", "local_off="); content = content.replace("oscCs=", "osc_cs="); writer.write(content); writer.flush(); os.flush(); os.close(); } fileIS.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } // // Get the URI of the model file. // URI touchoscURI = URI.createFileURI(touchoscFilePathList.get(0)); // // Demand load the resource for this file. // Resource resource = resourceSet.getResource(touchoscURI, true); Object obj = (Object) resource.getContents().get(0); if (obj instanceof TOP) { TOP top = (TOP) obj; reverseZOrders(top); return initAppFromTouchOsc(top.getLayout(), "horizontal".equals(top.getLayout().getOrientation()), "0".equals(top.getLayout().getMode())); } return null; }
From source file:de.alpharogroup.random.RandomExtensionsTest.java
/** * Test method for {@link RandomExtensions#getRandomString(java.lang.String, int)} . *//*from w w w.j ava 2 s. c om*/ @Test public void testRandomStringStringInt() { final CharBuffer charBuffer = CharBuffer.allocate(45); final int length = 5; final String chars = Constants.LCCHARSWNASC; charBuffer.put(chars); for (int i = 0; i < 100; i++) { final String randomString = RandomExtensions.getRandomString(chars, length); this.result = randomString.contains(charBuffer); AssertJUnit.assertTrue("", this.result); } }
From source file:jenkins.plugins.publish_over_cifs.CifsHostConfiguration.java
@SuppressWarnings("PMD.EmptyCatchBlock") private static String encode(final String raw) { if (raw == null) return null; final StringBuilder encoded = new StringBuilder(raw.length() * ESCAPED_BUILDER_SIZE_MULTIPLIER); final CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder(); final CharBuffer buffer = CharBuffer.allocate(1); for (final char c : raw.toCharArray()) { if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { encoded.append(c);/*from w ww. ja v a2s . c o m*/ } else { buffer.put(0, c); buffer.rewind(); try { final ByteBuffer bytes = encoder.encode(buffer); while (bytes.hasRemaining()) { final byte oneByte = bytes.get(); encoded.append('%'); encoded.append(toDigit((oneByte >> HI_TO_LOW_NIBBLE_BIT_SHIFT) & LOW_NIBBLE_BIT_MASK)); encoded.append(toDigit(oneByte & LOW_NIBBLE_BIT_MASK)); } } catch (final CharacterCodingException cce) { throw new BapPublisherException(Messages.exception_encode_cce(cce.getLocalizedMessage()), cce); } } } return encoded.toString(); }
From source file:com.gamesalutes.utils.ByteUtils.java
/** * Extends the size of <code>buf</code> to at least meet <code>minCap</code>. * If <code>buf</code> is too small, then a new buffer is allocated and * any existing contents in <code>buf</code> will be transfered. The position * of the new buffer will be that of the old buffer if it was not <code>null</code>, and * the previous mark will be discarded if one was set. * //ww w . j a va2 s .c o m * @param buf the input <code>ByteBuffer</code> * @param minCap the minimum capacity * @return a <code>CharBuffer</code> that can meet <code>minCap</code> */ public static CharBuffer growBuffer(CharBuffer buf, int minCap) { int myLimit = buf != null ? buf.limit() : 0; // limit can accomidate capacity requirements if (buf != null && myLimit >= minCap) return buf; int myCap = buf != null ? buf.capacity() : 0; // capacity can accomidate but limit is too small if (buf != null && myCap >= minCap) { buf.limit(myCap); return buf; } else //if(myCap < minCap) { CharBuffer newBuffer = null; if (myCap == 0) myCap = 1; while (myCap < minCap) myCap <<= 1; // if(buf != null && buf.isDirect()) // newBuffer = CharBuffer.allocateDirect(myCap); // else newBuffer = CharBuffer.allocate(myCap); // copy contents of original buffer if (buf != null) { int pos = buf.position(); buf.clear(); newBuffer.put(buf); newBuffer.position(pos); } return newBuffer; } }
From source file:com.cloudera.sqoop.io.TestLobFile.java
public void testSeekToRecord() throws Exception { // Seek past the first two records and read the third. Path p = new Path(TEMP_BASE_DIR, "seek.lob"); String[] records = { "this is the first record!", "here comes record number two. It is a bit longer.", "this is the third record. we can read it.", }; // Write the file and memorize when the third record starts. LobFile.Writer writer = LobFile.create(p, conf, true); int recNum = 0; long rec3Start = 0; for (String r : records) { Writer w = writer.writeClobRecord(r.length()); w.write(r);// w w w. ja v a 2s . co m w.close(); writer.finishRecord(); if (recNum == 1) { rec3Start = writer.tell(); LOG.info("Record three start: " + rec3Start); } recNum++; } writer.close(); // Now reopen the file for read, seek to the third record, and get it. LobFile.Reader reader = LobFile.open(p, conf); reader.seek(rec3Start); assertTrue(reader.next()); assertTrue(reader.isRecordAvailable()); assertEquals(rec3Start, reader.getRecordOffset()); Reader r = reader.readClobRecord(); CharBuffer buf = CharBuffer.allocate(records[2].length()); r.read(buf); r.close(); char[] chars = buf.array(); String s = new String(chars); assertEquals(records[2], s); r.close(); reader.close(); }
From source file:com.microsoft.tfs.core.util.FileEncodingDetector.java
/** * Tests whether the given byte array looks like an ANSI text file with the * default text encoding, i.e. can be decoded with the current ANSI * character set. In multi-byte character sets (like Japanese, for example) * the entire byte array might not be converted entirely, because at the end * of array it might contain a broken multi-byte character. We still accept * this kind of files as ANSI ones if the not converted reminder of the * array is short enough./*from w w w . j a v a2 s. com*/ * * @param bytes * the bytes to check for ANSI-ness (must not be <code>null</code>) * @param limit * the maximum number of bytes to read. * @return true if the given bytes look like part of an ANSI text file, * false if they do not (because they contain control characters or * other patterns). */ protected static boolean looksLikeANSI(final byte[] bytes, final int limit) { final Charset charSet = CodePageMapping.getCharset(FileEncoding.getDefaultTextEncoding().getCodePage()); final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, 0, limit); final CharBuffer charBuffer = CharBuffer.allocate(limit); final CharsetDecoder decoder = charSet.newDecoder(); decoder.onUnmappableCharacter(CodingErrorAction.REPORT); decoder.onMalformedInput(CodingErrorAction.REPORT); final CoderResult rc = decoder.decode(byteBuffer, charBuffer, true); if (!rc.isError()) { return true; } else { return byteBuffer.position() > limit - 5; } }