Showing posts with label input stream. Show all posts
Showing posts with label input stream. Show all posts

Thursday, 9 February 2023

Java: Convert InputStream to string

In this post, I am going to explain how to convert an InputStream to a String.

 

Approach 1: Read the stream character by character and append it to the StringBuilder.

public static String inputStreamToString1(InputStream inputStream, Charset charSet) throws IOException {
	StringBuilder stringBuilder = new StringBuilder();
	try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, charSet))) {
		int c = 0;
		while ((c = reader.read()) != -1) {
			stringBuilder.append((char) c);
		}
	}

	return stringBuilder.toString();
}

 

Approach 2: Using BufferedReader lines() method.

public static String inputStreamToString2(InputStream inputStream, Charset charSet) throws IOException {

	try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charSet))) {
		return reader.lines().collect(Collectors.joining("\n"));
	}

}

 

Approach 3: Using InputStream.readAllBytes() method.

 

'readAllBytes()' method is available from Java9, it returns a byte array containing the bytes read from this input stream.

public static String inputStreamToString3(InputStream inputStream, Charset charSet) throws IOException {
	return new String(inputStream.readAllBytes(), charSet);
}

Find the below working application.

 

App.java

package com.sample.app;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

public class App {

	public static String inputStreamToString1(InputStream inputStream, Charset charSet) throws IOException {
		StringBuilder stringBuilder = new StringBuilder();
		try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, charSet))) {
			int c = 0;
			while ((c = reader.read()) != -1) {
				stringBuilder.append((char) c);
			}
		}

		return stringBuilder.toString();
	}

	public static String inputStreamToString2(InputStream inputStream, Charset charSet) throws IOException {

		try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charSet))) {
			return reader.lines().collect(Collectors.joining("\n"));
		}

	}

	public static String inputStreamToString3(InputStream inputStream, Charset charSet) throws IOException {
		return new String(inputStream.readAllBytes(), charSet);
	}

	public static void main(String[] args) throws IOException {
		InputStream inputStream1 = new ByteArrayInputStream("Hello World".getBytes());
		InputStream inputStream2 = new ByteArrayInputStream("Hello World".getBytes());
		InputStream inputStream3 = new ByteArrayInputStream("Hello World".getBytes());

		String str1 = inputStreamToString1(inputStream1, StandardCharsets.UTF_8);
		String str2 = inputStreamToString1(inputStream2, StandardCharsets.UTF_8);
		String str3 = inputStreamToString1(inputStream3, StandardCharsets.UTF_8);

		System.out.println(str1);
		System.out.println(str2);
		System.out.println(str3);
	}
}

Output

Hello World
Hello World
Hello World



You may like

file and stream programs in Java

Get file basic file attributes in Java

check whether a file is executable or not in Java

Check whether a directory has some files or not

Check given path is a file and not a symbolic link in Java

Check given path is a directory and not a symbolic link in Java

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?