Java String to InputStream

Chaîne Java vers InputStream

1. Vue d'ensemble

Dans ce rapide didacticiel, nous allons voir commentconvert a standard String to an InputStream en utilisant Java, Guava et la bibliothèque Apache Commons IO.

Cet article fait partie dethe “Java – Back to Basic” series ici par exemple.

2. Convertir avec Java brut

Commençons par un exemple simple utilisant Java pour effectuer la conversion - en utilisant un tableau intermédiairebyte:

@Test
public void givenUsingPlainJava_whenConvertingStringToInputStream_thenCorrect()
  throws IOException {
    String initialString = "text";
    InputStream targetStream = new ByteArrayInputStream(initialString.getBytes());
}

Notez que la méthodegetBytes() encode ceString en utilisant le jeu de caractères par défaut de la plate-forme afin d’éviter tout comportement indésirable, vous pouvez utilisergetBytes(Charset charset) etcontrol the encoding process.

3. Convertir avec la goyave

Guava ne fournit pas de méthode de conversion directe, mais nous permet d'obtenir unReader de la chaîne - à ce stade, il est facile d'obtenir lesInputStream:

@Test
public void givenUsingGuava_whenConvertingStringToInputStream_thenCorrect()
  throws IOException {
    String initialString = "text";
    InputStream targetStream =
     new ReaderInputStream(CharSource.wrap(initialString).openStream());
}

4. Convertir avec Commons IO

Enfin, la bibliothèque Apache Commons IO constitue une excellente solution directe:

@Test
public void givenUsingCommonsIO_whenConvertingStringToInputStream_thenCorrect()
  throws IOException {
    String initialString = "text";
    InputStream targetStream = IOUtils.toInputStream(initialString);
}

Enfin, notez que nous laissons le flux d'entrée ouvert dans ces exemples, n'oubliez pas declose it when you’re done.

Voilà - trois façons simples et concises d’obtenir unInputStream d’une chaîne simple.