Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Wednesday, 3 May 2023

Convert a throwable or an exception stack trace to string in Java

Following snippet converts the exception or a throwable stack trace to string representation.

public static String throwableToString(Throwable t) {

	try (StringWriter stringWriter = new StringWriter(); PrintWriter pw = new PrintWriter(stringWriter, true);) {
		t.printStackTrace(pw);
		pw.flush();
		return stringWriter.toString();
	} catch (IOException e) {
		e.printStackTrace(System.err);
		return "Error occurred : " + e.getMessage();
	}
}

 

Find the below working application.


 

ThrowableToString.java
package com.sample.app.strings;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

public class ThrowableToString {

	public static String throwableToString(Throwable t) {

		try (StringWriter stringWriter = new StringWriter(); PrintWriter pw = new PrintWriter(stringWriter, true);) {
			t.printStackTrace(pw);
			pw.flush();
			return stringWriter.toString();
		} catch (IOException e) {
			e.printStackTrace(System.err);
			return "Error occurred : " + e.getMessage();
		}
	}

	public static void main(String[] args) {
		try {
			int result = 10 / 0;
			System.out.println(result);
		} catch (Throwable t) {
			System.out.println(throwableToString(t));
		}
	}

}

 

Output

java.lang.ArithmeticException: / by zero
	at com.sample.app.strings.ThrowableToString.main(ThrowableToString.java:23)

 

  

Previous                                                 Next                                                 Home

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, 12 November 2022

Check whether a string has any non-white space character or not

Write a function that takes a string as input and return true, if the string contain any non-whitespace character, else false.

 

A character is a Java whitespace character if and only if it satisfies one of the following criteria:

a.   It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').It is '\t', U+0009 HORIZONTAL TABULATION.

b.   It is '\n', U+000A LINE FEED.

c.    It is '\u000B', U+000B VERTICAL TABULATION.

d.   It is '\f', U+000C FORM FEED.

e.   It is '\r', U+000D CARRIAGE RETURN.

f.     It is '\u001C', U+001C FILE SEPARATOR.

g.   It is '\u001D', U+001D GROUP SEPARATOR.

h.   It is '\u001E', U+001E RECORD SEPARATOR.

i.     It is '\u001F', U+001F UNIT SEPARATOR.

 

Signature

public static boolean hasNonWhitespaceChar(final String str)

 


Find the below working application.

 

StringNonWhitspaceCharCheck.java
package com.sample.app.strings;

public class StringNonWhitspaceCharCheck {

	/**
	 * 
	 * @param str
	 * 
	 * @return true if str contains any non whitespace characters, else false.
	 */
	public static boolean hasNonWhitespaceChar(final String str) {
		if (str == null || str.isEmpty()) {
			return false;
		}

		final int length = str.length();
		for (int i = 0; i < length; i++) {
			if (Character.isWhitespace(str.charAt(i))) {
				continue;
			}

			return true;
		}
		return false;
	}

	public static void main(String[] args) {
		String str1 = "\t  \n\r";
		String str2 = "\t a  \n";
		
		System.out.println("is str1 contain any non whitespace character : "+ hasNonWhitespaceChar(str1));
		System.out.println("is str2 contain any non whitespace character : "+ hasNonWhitespaceChar(str2));
	}
}

 

Output

is str1 contain any non whitespace character : false
is str2 contain any non whitespace character : true

 

References

https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html

 


 

Previous                                                 Next                                                 Home

Saturday, 10 September 2022

Convert OutputStream to String in Java

‘java.io.OutputStream’  is the abstract superclass of all the classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink/destination.

 

Following examples explain how to convert different a ByteArrayOutputStream object to string in Java.

 

Example 1: Convert ByteArrayOutputStream to string.

 

Get the byte array from ByteArrayOutputStream object.

byte[] byteArr = byteArrayOutputStream.toByteArray();

Initialize the string using byte array.

String str2 = new String(byteArr);

Find the below working application.

 

OutputStreamToStringDemo1.java

package com.sample.app.streams;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class OutputStreamToStringDemo1 {

	public static void main(String[] args) throws IOException {
		try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
			String str1 = "Hello World!!!!";
			byteArrayOutputStream.write(str1.getBytes());

			byte[] byteArr = byteArrayOutputStream.toByteArray();
			String str2 = new String(byteArr);

			System.out.println("str1 : " + str1);
			System.out.println("str2 : " + str2);
		}

	}

}

Output

str1 : Hello World!!!!
str2 : Hello World!!!!

Example 2: Using toString method of ByteArrayOutputStream.

ByteArrayOutputString#toString method converts the buffer's contents into a string decoding bytes using the platform's default character set.

String str2 = byteArrayOutputStream.toString();

OutputStreamToStringDemo2.java

package com.sample.app.streams;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class OutputStreamToStringDemo2 {

	public static void main(String[] args) throws IOException {
		try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
			String str1 = "Hello World!!!!";
			byteArrayOutputStream.write(str1.getBytes());

			String str2 = byteArrayOutputStream.toString();

			System.out.println("str1 : " + str1);
			System.out.println("str2 : " + str2);
		}

	}

}

Output

str1 : Hello World!!!!
str2 : Hello World!!!!

You can even set the character set to decode the byte array to string using following toString methods.

public synchronized String toString(Charset charset)

public synchronized String toString(String charsetName)

Converts the buffer's contents into a string by decoding the bytes using the specified charset.

 

An invocation of this method of the form

String str = byteArrayOutputStream.toString("UTF-8");

 

behaves in exactly the same way as the below expression.

String str = byteArrayOutputStream.toString(StandardCharsets.UTF_8);

 


OutputStreamToStringDemo3.java

package com.sample.app.streams;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class OutputStreamToStringDemo3 {

	public static void main(String[] args) throws IOException {
		try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
			String str1 = "Hello World!!!!";
			byteArrayOutputStream.write(str1.getBytes());

			String str2 = byteArrayOutputStream.toString("UTF-8");
			String str3 = byteArrayOutputStream.toString(StandardCharsets.UTF_8);

			System.out.println("str1 : " + str1);
			System.out.println("str2 : " + str2);
			System.out.println("str3 : " + str3);
		}

	}

}

Output

str1 : Hello World!!!!
str2 : Hello World!!!!
str3 : Hello World!!!!



You may like

Copy the content of file to other location

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?

Tuesday, 19 July 2022

How to get the string size in bits?

'string.getBytes(stringEncoding).length * 8' return the string length in bits.

 

StringLengthInBits.java

package com.sample.app;

import java.nio.charset.StandardCharsets;

public class StringLengthInBits {

	public static void main(String[] args) {
		String str1 = "Hello World";

		System.out.println("length in " + StandardCharsets.ISO_8859_1 + " is "
				+ str1.getBytes(StandardCharsets.ISO_8859_1).length * 8);

		System.out.println("length in " + StandardCharsets.US_ASCII + " is "
				+ str1.getBytes(StandardCharsets.US_ASCII).length * 8);

		System.out.println("length in " + StandardCharsets.UTF_16 + " is " + str1.getBytes(StandardCharsets.UTF_16).length * 8);

		System.out.println("length in " + StandardCharsets.UTF_16BE + " is "
				+ str1.getBytes(StandardCharsets.UTF_16BE).length * 8);

		System.out.println("length in " + StandardCharsets.UTF_16LE + " is "
				+ str1.getBytes(StandardCharsets.UTF_16LE).length * 8);

		System.out.println("length in " + StandardCharsets.UTF_8 + " is " + str1.getBytes(StandardCharsets.UTF_8).length * 8);
	}

}

 

Output

length in ISO-8859-1 is 88
length in US-ASCII is 88
length in UTF-16 is 192
length in UTF-16BE is 176
length in UTF-16LE is 176
length in UTF-8 is 88

  

Previous                                                 Next                                                 Home