SlackStack
SlackStack

Reputation: 79

How can I convert a String into a DataInputStream type in Java?

Is there any way to do this conversion in Java? I have tried the suggested tips online for converting a String into an InputStream type, but it is not the same, and there is nothing else online that I can find.

Upvotes: 0

Views: 2270

Answers (2)

A_01
A_01

Reputation: 1141

This might help

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;

public class MyApp {

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

        InputStream is = new ByteArrayInputStream("hi I am test".getBytes(Charset.forName("UTF-8")));

        DataInputStream dataIn = new DataInputStream(is);
        while (dataIn.available() > 0) {
            String k = dataIn.readLine();
            System.out.print(k + " ");
        }
    }

}

Upvotes: 1

KhAn SaAb
KhAn SaAb

Reputation: 5366

Hope below code will help you to convert String into DataInputStream

String string = "Sample String";
InputStream inputStream = new ByteArrayInputStream(string.getBytes(Charset.forName("UTF-8")));
DataInputStream dis = new DataInputStream(inputStream);

Upvotes: 1

Related Questions