Saturday 10 September 2022

Convert string to InputStream in Java

InputStream is an abstract superclass of all classes representing an input stream of bytes.

 

By initializing the ByteArrayInputStream using string byte array, we can get a InputStream object with string content.

String str = "line 1\nline 2\nline 3";
InputStream inputStream = new ByteArrayInputStream(str.getBytes()

Find the below working application.

 

StringToInputStreamDemo1.java

package com.sample.app.streams;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StringToInputStreamDemo1 {

	public static void main(String[] args) {
		String str = "line 1\nline 2\nline 3";

		try (InputStream inputStream = new ByteArrayInputStream(str.getBytes());
				BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {

			String info = null;
			while ((info = br.readLine()) != null) {
				System.out.println(info);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

Output

line 1
line 2
line 3

Get the InputStream from substring of string

Using the following constrcutor, we can get the InputStream from the string substring.

 

public ByteArrayInputStream(byte buf[], int offset, int length) 

'offset' specifies the offset in the buffer of the first byte to read and 'length' specifies the maximum number of bytes to read from the buffer.

 

Example

String str = "line 1\nline 2\nline 3";
InputStream inputStream = new ByteArrayInputStream(str.getBytes(), 7, 7);

Find the below working application.


 

StringToInputStreamDemo2.java

package com.sample.app.streams;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StringToInputStreamDemo2 {

	public static void main(String[] args) {
		String str = "line 1\nline 2\nline 3";

		try (InputStream inputStream = new ByteArrayInputStream(str.getBytes(), 7, 7);
				BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {

			String info = null;
			while ((info = br.readLine()) != null) {
				System.out.println(info);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

Output

line 2



You may like

file and stream programs in Java

Convert OutputStream to String in Java

Write byte array to a file

How to download a binary file in Java?

How to process a huge file line by line in Java?

How to get the directory size in Java?

No comments:

Post a Comment