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

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?

Monday, 27 June 2022

Implement ByteBuffer input stream

Channels and Buffers are the basic building blocks of Java NIO. Channels are analogous to the streams in IO. All the data should go via channels. If you send any data to channel, the data is placed in a buffer. Any data that is read from a channel is read into a buffer. Buffer is a container that holds some data.

 

Let’s create ByteBufferInputStream by extending InputStream class.

 


ByteBufferInputStream.java

package com.sample.app.streams;

import static java.lang.Math.max;
import static java.lang.Math.min;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

public class ByteBufferInputStream extends InputStream {

	private final ByteBuffer byteBuffer;

	public ByteBufferInputStream(final ByteBuffer byteBuffer) {
		this.byteBuffer = byteBuffer.slice();
	}

	@Override
	public int read() {
		// a & 0xff will give the lowest 8 bits from a. If a is less than 255, it'll
		// return the same number.
		if (byteBuffer.hasRemaining()) {
			return 0xff & byteBuffer.get();
		}

		return -1;
	}

	@Override
	public int read(final byte b[], final int off, final int len) {
		final int minLength = min(len, byteBuffer.remaining());
		byteBuffer.get(b, off, minLength);
		return minLength;
	}

	@Override
	public long skip(long noOfLinesToSkip) {
		final long minLinesToSlip = min(byteBuffer.remaining(), max(noOfLinesToSkip, 0));
		byteBuffer.position((int) (byteBuffer.position() + minLinesToSlip));
		return minLinesToSlip;
	}

	@Override
	public synchronized int available() {
		return byteBuffer.remaining();
	}

	@Override
	public void close() throws IOException {
		// not applicable
	}
}

 

App.java

package com.sample.app;

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

import com.sample.app.streams.ByteBufferInputStream;

public class App {

	public static void main(String[] args) throws IOException {
		ByteBuffer byteBuffer = ByteBuffer.allocate(100);
		byteBuffer.put("one\n".getBytes(StandardCharsets.UTF_8));
		byteBuffer.put("two\n".getBytes(StandardCharsets.UTF_8));
		byteBuffer.put("three\n".getBytes(StandardCharsets.UTF_8));
		byteBuffer.put("four\n".getBytes(StandardCharsets.UTF_8));
		byteBuffer.put("five\n".getBytes(StandardCharsets.UTF_8));

		byteBuffer.flip();

		try (ByteBufferInputStream byteBufferInputStream = new ByteBufferInputStream(byteBuffer)) {
			StringBuilder stringBuilder = new StringBuilder();

			int data;
			while ((data = byteBufferInputStream.read()) != -1) {
				stringBuilder.append((char) data);
			}

			System.out.println(stringBuilder.toString());
		}

	}

}

 

Output

one
two
three
four
five

 

 

 

 

  

Previous                                                 Next                                                 Home

Sunday, 6 March 2022

File programs in Java

      Get File path separator
      Java Properties file
      Compress and archive files in zip format
      Decompress files from zip file
      File utilities application using Guava package
      Check contents of two files are equal or not
      Encrypt and decrypt XML file in Java
      Create Password Protected zip file in Java
      Place a file in project class path
      Accessing meta data of a file (All attributes of file)
      Set Unique Identifier to File in Java
      Set File permissions in Java
      File Tail implementation in Java
      Launch URI Scheme over java file
      DigestInputStream & DigestOutputStream Example
      Move file to recycle bin
      Generate content hash of a file
      HOW TO GENERATE SHA1 HASH VALUE OF FILE
      HOW TO GENERATE MD5 HASH VALUE OF FILE
      List contents of a zip file
      Split file path using system file separator symbol
      Split the string using file Path separator
      File.separator vs File.pathSeparator
      Encrypt and Decrypt file/stream in Java
      Print all the file names recursively
      How to write multiple input streams to a file
      Working with RandomAccessFile in Java
      Java write to a file using BufferedWriter
      Java write to a file using FileWriter
       Java: Programmatically import certificate to cacerts file
      Apache commons io: Download a file from url
      Convert xml file to csv
      Redirect System.out.println statements to a stream or file
      Redirect System.err.println statements to a stream or file
      Append text to a file
      Create and write text content to a file
      Create and write byte array to a file
      Read plain text file in Java
      Copy file from one location to another
      Search for files in a folder
       Print all the file names in a directory and sub directories
      Read last n lines of a file
      Escape equal sign in properties file
      Open a file
      Convert InputStream to ByteArray
      Convert file to byte array
      Java: Get content hash of the file
      Read file content as string
      Read file content as string in one line
      Get file name by removing extension
      Sort the files by their last modified date
      Sort files by their name
      Sort files by their size
      Get File size in java
      List files by their created time
      Create file parent directories if they are not exist
      Get file name from absolute path
      Count number of lines in a file
      Download file from Internet using Java
      Get the content of resource file as string
      Get the resource file path
      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 in Java?
      How to process a large file in chunks?
      How to get the directory size in Java?
      Convert OutputStream to String in Java
      Convert string to InputStream in Java
      Read the data from BufferedReader in Java
      Read file content using BufferedReader in Java
      Touch the file in Java (Update the file timestamp)
      Get POSIX file attributes 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 in Java
      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
      Convert InputStream to string in Java
      Write InputStream to a file in Java
      File separator, separatorChar, pathSeparator, pathSeparatorChar in Java
      Implement an Output stream that writes the data to two output streams
      Check whether directory can be accessed and has read and write privileges in Java
      Get the hash or message digest of a file in Java
      Copy InputStream to OutputStream in Java

Monday, 28 June 2021

Lucene: How to get TokenStream?

TokenStream represents an intermediate data format between different components of analysis process and it is an enumeration of tokens. Analyzer can take a Reader as input and output TokenStream.

 

Example

Analyzer analyzer = new EnglishAnalyzer();
Reader reader = new StringReader("Text to be passed");
TokenStream tokenStream = analyzer.tokenStream("myField", reader);

 

App.java

package com.sample.app;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.en.EnglishAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;

public class App {

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

		try (Analyzer analyzer = new EnglishAnalyzer()) {
			Reader reader = new StringReader("Java is a Programming Language");
			TokenStream tokenStream = analyzer.tokenStream("myField", reader);

			CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);

			tokenStream.reset();

			while (tokenStream.incrementToken()) {
				System.out.println(charTermAttribute.toString());
			}
		}

	}

}

 

Output

java
program
languag

 


  

Previous                                                    Next                                                    Home

Sunday, 15 March 2020

Ignore duplicates while producing map from a stream

Using merge function, we can specify how to resolve collisions associated with same key.

Example
Map<String, String> map = emps.stream()
.collect(Collectors.toMap(Employee::getFirstName, Employee::getLastName, (value1, value2) -> {
         return value1;
}));

Above snippet specifies in case of collisions take first value.

Employee.java
package com.sample.app.model;

public class Employee {
 private String firstName;
 private String lastName;

 public Employee(String firstName, String lastName) {
  super();
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
  result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Employee other = (Employee) obj;
  if (firstName == null) {
   if (other.firstName != null)
    return false;
  } else if (!firstName.equals(other.firstName))
   return false;
  if (lastName == null) {
   if (other.lastName != null)
    return false;
  } else if (!lastName.equals(other.lastName))
   return false;
  return true;
 }

}

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.sample.app.model.Employee;

public class App {

 public static void main(String args[]) throws InterruptedException {
  Employee emp1 = new Employee("Ram", "Gurram");
  Employee emp2 = new Employee("Siva", "Ponnam");
  Employee emp3 = new Employee("Sailaja", "Navakotla");
  Employee emp4 = new Employee("Ram", "Battu");

  List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4);

  Map<String, String> map = emps.stream()
    .collect(Collectors.toMap(Employee::getFirstName, Employee::getLastName, (value1, value2) -> {
     return value1;
    }));

  for (String firstName : map.keySet()) {
   System.out.println(firstName + " , " + map.get(firstName));
  }
 }

}

Output
Sailaja , Navakotla
Siva , Ponnam
Ram , Gurram

You may like