Tabnine Logo
String.getBytes
Code IndexAdd Tabnine to your IDE (free)

How to use
getBytes
method
in
java.lang.String

Best Java code snippets using java.lang.String.getBytes (Showing top 20 results out of 151,641)

canonical example by Tabnine

public void postRequest(String urlStr, String jsonBodyStr) throws IOException {
  URL url = new URL(urlStr);
  HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
  httpURLConnection.setDoOutput(true);
  httpURLConnection.setRequestMethod("POST");
  httpURLConnection.setRequestProperty("Content-Type", "application/json");
  try (OutputStream outputStream = httpURLConnection.getOutputStream()) { 
   outputStream.write(jsonBodyStr.getBytes());
   outputStream.flush();
  }
  if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) {
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        // ... do something with line
      }
    }
  } else {
    // ... do something with unsuccessful response
  }
}
origin: google/guava

public void testRfc2202_hmacMd5_case2() {
 byte[] key = "Jefe".getBytes(UTF_8);
 String data = "what do ya want for nothing?";
 checkMd5("750c783e6ab0b503eaa86e310a5db738", key, data);
}
origin: google/guava

private static Manifest manifest(String content) throws IOException {
 InputStream in = new ByteArrayInputStream(content.getBytes(US_ASCII));
 Manifest manifest = new Manifest();
 manifest.read(in);
 return manifest;
}
origin: google/guava

public void testRfc2202_hmacSha1_case2() {
 byte[] key = "Jefe".getBytes(UTF_8);
 String data = "what do ya want for nothing?";
 checkSha1("effcdf6ae5eb2fa2d27416d5f184df9c259a7c79", key, data);
}
origin: google/guava

public void testSomeOtherKnownValues() {
 assertCrc(0x22620404, "The quick brown fox jumps over the lazy dog".getBytes(UTF_8));
 assertCrc(0xE3069283, "123456789".getBytes(UTF_8));
 assertCrc(0xf3dbd4fe, "1234567890".getBytes(UTF_8));
 assertCrc(0xBFE92A83, "23456789".getBytes(UTF_8));
}
origin: google/guava

@SuppressWarnings("deprecation") // testing a deprecated method
public void testWriteBytes() throws IOException {
 /* Write out various test values in LITTLE ENDIAN FORMAT */
 out.writeBytes("r\u00C9sum\u00C9");
 byte[] data = baos.toByteArray();
 /* Setup input streams */
 DataInput in = new DataInputStream(new ByteArrayInputStream(data));
 /* Read in various values NORMALLY */
 byte[] b = new byte[6];
 in.readFully(b);
 assertEquals("r\u00C9sum\u00C9".getBytes(Charsets.ISO_8859_1), b);
}
origin: google/guava

public void testNullOutputStream() throws Exception {
 // create a null output stream
 OutputStream nos = ByteStreams.nullOutputStream();
 // write to the output stream
 nos.write('n');
 String test = "Test string for NullOutputStream";
 nos.write(test.getBytes());
 nos.write(test.getBytes(), 2, 10);
 // nothing really to assert?
 assertSame(ByteStreams.nullOutputStream(), ByteStreams.nullOutputStream());
}
origin: google/guava

public void testKnownInputs() throws Exception {
 String knownOutput = "9753980fe94daa8ecaa82216519393a9";
 String input = "The quick brown fox jumps over the lazy dog";
 Mac mac = Mac.getInstance("HmacMD5");
 mac.init(MD5_KEY);
 mac.update(input.getBytes(UTF_8));
 assertEquals(knownOutput, HashCode.fromBytes(mac.doFinal()).toString());
 assertEquals(knownOutput, HashCode.fromBytes(mac.doFinal(input.getBytes(UTF_8))).toString());
 assertEquals(knownOutput, Hashing.hmacMd5(MD5_KEY).hashString(input, UTF_8).toString());
 assertEquals(knownOutput, Hashing.hmacMd5(MD5_KEY).hashBytes(input.getBytes(UTF_8)).toString());
}
origin: google/guava

@GwtIncompatible // Reader
private static void testStreamingDecodes(BaseEncoding encoding, String encoded, String decoded)
  throws IOException {
 byte[] bytes = decoded.getBytes(UTF_8);
 InputStream decodingStream = encoding.decodingStream(new StringReader(encoded));
 for (int i = 0; i < bytes.length; i++) {
  assertThat(decodingStream.read()).isEqualTo(bytes[i] & 0xFF);
 }
 assertThat(decodingStream.read()).isEqualTo(-1);
 decodingStream.close();
}
origin: google/guava

public void testReallySimpleFingerprints() {
 assertEquals(8581389452482819506L, fingerprint("test".getBytes(UTF_8)));
 // 32 characters long
 assertEquals(-4196240717365766262L, fingerprint(Strings.repeat("test", 8).getBytes(UTF_8)));
 // 256 characters long
 assertEquals(3500507768004279527L, fingerprint(Strings.repeat("test", 64).getBytes(UTF_8)));
}
origin: google/guava

 public void testInvalidUnicodeHasherPutString() {
  String str =
    new String(
      new char[] {'a', Character.MIN_HIGH_SURROGATE, Character.MIN_HIGH_SURROGATE, 'z'});
  assertEquals(
    murmur3_32().hashBytes(str.getBytes(Charsets.UTF_8)),
    murmur3_32().newHasher().putString(str, Charsets.UTF_8).hash());
 }
}
origin: google/guava

@AndroidIncompatible // https://code.google.com/p/android/issues/detail?id=196848
public void testUtf16Expected() {
 byte[] hardcodedExpected = utf16ExpectedWithBom;
 byte[] computedExpected = "r\u00C9sum\u00C9".getBytes(Charsets.UTF_16);
 assertEquals(hardcodedExpected, computedExpected);
}
origin: google/guava

@SuppressWarnings("deprecation")
public void testSimpleStringUtf8() {
 assertEquals(
   murmur3_32().hashBytes("ABCDefGHI\u0799".getBytes(Charsets.UTF_8)),
   murmur3_32().hashString("ABCDefGHI\u0799", Charsets.UTF_8));
}
origin: google/guava

public void testHash() throws IOException {
 ByteSource byteSource = new TestByteSource("hamburger\n".getBytes(Charsets.US_ASCII));
 // Pasted this expected string from `echo hamburger | md5sum`
 assertEquals("cfa0c5002275c90508338a5cdb2a9781", byteSource.hash(Hashing.md5()).toString());
}
origin: google/guava

public void testNewDataInput_readUTF() {
 byte[] data = new byte[17];
 data[1] = 15;
 System.arraycopy("Kilroy was here".getBytes(Charsets.UTF_8), 0, data, 2, 15);
 ByteArrayDataInput in = ByteStreams.newDataInput(data);
 assertEquals("Kilroy was here", in.readUTF());
}
origin: google/guava

public void testToByteArray() throws IOException {
 File asciiFile = getTestFile("ascii.txt");
 File i18nFile = getTestFile("i18n.txt");
 assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII), Files.toByteArray(asciiFile)));
 assertTrue(Arrays.equals(I18N.getBytes(Charsets.UTF_8), Files.toByteArray(i18nFile)));
 assertTrue(Arrays.equals(I18N.getBytes(Charsets.UTF_8), Files.asByteSource(i18nFile).read()));
}
origin: google/guava

static TestSuite suiteForString(
  ByteSourceFactory factory, String string, String name, String desc) {
 TestSuite suite = suiteForBytes(factory, string.getBytes(Charsets.UTF_8), name, desc, true);
 CharSourceFactory charSourceFactory = SourceSinkFactories.asCharSourceFactory(factory);
 suite.addTest(
   CharSourceTester.suiteForString(
     charSourceFactory, string, name + ".asCharSource[Charset]", desc));
 return suite;
}
origin: google/guava

public void testNewDataOutput_writeUTF() {
 ByteArrayDataOutput out = ByteStreams.newDataOutput();
 out.writeUTF("r\u00C9sum\u00C9");
 byte[] expected = "r\u00C9sum\u00C9".getBytes(Charsets.UTF_8);
 byte[] actual = out.toByteArray();
 // writeUTF writes the length of the string in 2 bytes
 assertEquals(0, actual[0]);
 assertEquals(expected.length, actual[1]);
 assertEquals(expected, Arrays.copyOfRange(actual, 2, actual.length));
}
origin: google/guava

public void testNullPointers() {
 NullPointerTester tester =
   new NullPointerTester()
     .setDefault(byte[].class, "secret key".getBytes(UTF_8))
     .setDefault(HashCode.class, HashCode.fromLong(0));
 tester.testAllPublicStaticMethods(Hashing.class);
}
origin: google/guava

public void testNewDataInput_readChar() {
 byte[] data = "qed".getBytes(Charsets.UTF_16BE);
 ByteArrayDataInput in = ByteStreams.newDataInput(data);
 assertEquals('q', in.readChar());
 assertEquals('e', in.readChar());
 assertEquals('d', in.readChar());
}
java.langStringgetBytes

Javadoc

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

The behavior of this method when this string cannot be encoded in the default charset is unspecified. The java.nio.charset.CharsetEncoder class should be used when more control over the encoding process is required.

Popular methods of String

  • equals
  • length
    Returns the number of characters in this string.
  • substring
    Returns a string containing a subsequence of characters from this string. The returned string shares
  • startsWith
    Compares the specified string to this string, starting at the specified offset, to determine if the
  • format
    Returns a formatted string, using the supplied format and arguments, localized to the given locale.
  • split
    Splits this string using the supplied regularExpression. See Pattern#split(CharSequence,int) for an
  • trim
  • valueOf
    Creates a new string containing the specified characters in the character array. Modifying the chara
  • indexOf
  • endsWith
    Compares the specified string to this string to determine if the specified string is a suffix.
  • toLowerCase
    Converts this string to lower case, using the rules of locale.Most case mappings are unaffected by t
  • contains
    Determines if this String contains the sequence of characters in the CharSequence passed.
  • toLowerCase,
  • contains,
  • <init>,
  • equalsIgnoreCase,
  • replace,
  • isEmpty,
  • charAt,
  • hashCode,
  • lastIndexOf

Popular in Java

  • Making http requests using okhttp
  • getOriginalFilename (MultipartFile)
    Return the original filename in the client's filesystem.This may contain path information depending
  • getResourceAsStream (ClassLoader)
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • Runnable (java.lang)
    Represents a command that can be executed. Often used to run code in a different Thread.
  • Socket (java.net)
    Provides a client-side TCP socket.
  • TreeSet (java.util)
    TreeSet is an implementation of SortedSet. All optional operations (adding and removing) are support
  • Modifier (javassist)
    The Modifier class provides static methods and constants to decode class and member access modifiers
  • SSLHandshakeException (javax.net.ssl)
    The exception that is thrown when a handshake could not be completed successfully.
  • Servlet (javax.servlet)
    Defines methods that all servlets must implement. A servlet is a small Java program that runs within
  • Top plugins for Android Studio
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now