Convert Java File to InputStream | Tracedynamics

Convert Java File to InputStream | Tracedynamics

In this article, we have discussed how to convert a java file to an InputStream. There is 5 very easy way to convert a java file to InputStream by Using Traditional java IO Package, using Java 8, Using Apache Common IO Library, Using Guava Library. Let’s look at some of the Java InputStream examples in this tutorial. Let’s convert a File to an InputStream in numerous ways of implementation. Before starting to convert a file to InputStream, let’s know what is an InputStream and 

What is InputStream?

InputStream is an abstract class of Java API.

Its a superclass of all classes defining an input stream of bytes.

InputStream extends Object and its implemented Interfaces are Closeable, AutoCloseable.

InputStream Subclasses are AudioInputStream, ByteArrayInputStream, FileInputStream, FilterInputStream, InputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream.

These are particularly helpful for reading and write operations on file streams or input files.

Again let’s go in detail about first, second, third ways of converting File to InputStream.

Convert using Traditional Java IO Package

Our first method to convert Java File To Inputstream.

In the first place, let’s leverage the Java IO package to convert a File format to different InputStream’s.

Of course under the IO package, the first one we use is FileInputStream.

Following Java code read a file from the file path/folder directory location.

Furthermore it converts into InputStream using method FileInputStream().

public static void main(String[] args) throws IOException {
	try {
		File file = new File("src/resources/hello.txt");
		InputStream is = new FileInputStream(file);
		System.out.println("InputStream is: " + is);
        is.close();
	} catch (Exception e) {
			e.printStackTrace();
	}
}

Output:
InputStream is: [email protected]

As per output, the program reads a txt file and converts a File to an InputStream.

of course, next is by using SequenceInputStream.

Java program concatenates the input data stream of two files to a single InputStream.

public static void main(String[] args) throws IOException {
try {
	File file = new File("src/resources/Hello.txt");
	File file2 = new File("src/resources/Test.txt");
	InputStream firstIS = new FileInputStream(file);
	InputStream secondIS = new FileInputStream(file2);
	InputStream is = new SequenceInputStream(firstIS, secondIS);
	System.out.println("SequenceInputStream is: "+is);
    firstIS.close();
	secondIS.close();
	is.close();
    } catch (Exception e) {
	  e.printStackTrace();
	}
}

Output:
SequenceInputStream is: [email protected]

Not to mention, finally using DataInputStream.

This will read primitive data stream or binary data from a file.

public static void main(String[] args) throws IOException {
try {
	 File file = new File("src/resources/Hello.txt");
 	 InputStream is = new DataInputStream(new FileInputStream(file));
  	 System.out.println("DataInputStream is: "+is);	
     is.close();
	 } catch (Exception e) {
	  e.printStackTrace();
	}
}

Output:
DataInputStream is: [email protected]

These just for you,

File to InputStream using Java 8

Using Java 8 method to convert Java File To Inputstream.

Using Java 8, we can save the input stream to file as below

public static void main(String[] args) throws IOException {
		String TARGET_PATH = "C:\\test\\wikipedia.txt";
	try {
		URI uri = URI.create("https://www.wikipedia.com/");
		InputStream inputStream = uri.toURL().openStream();
		Files.copy(inputStream, Paths.get(TARGET_PATH),StandardCopyOption.REPLACE_EXISTING);
		System.out.println("File copied to location: " + TARGET_PATH);
	} catch (Exception e) {
		e.printStackTrace();
	}

}

Output:
File copied to location: C:\test\wikipedia.txt

By using Apache Commons IO Library

Using Apache Commons IO Library API, we can convert java File to an InputStream as below.

public static void main(String[] args) throws IOException {
try {
	File file = new File("src/resources/Hello.txt");
	InputStream is = FileUtils.openInputStream(file);
	System.out.println("Apache Commons InputStream is: "+is);		
	} catch (Exception e) {
	  e.printStackTrace();
	}
}

Output:
Apache Commons InputStream is: [email protected]

Apache Commons IO library can be download from here.

Java File to InputStream using Guava Library

It is my favorite, using Guava Library converts to inputstream in java.

As we know Guava is an open-source Java API library from Google.

Using Guava we can convert File to an InputStream with below source code.

public static void main(String[] args) throws IOException {
try {
	File file = new File("src/resources/Hello.txt");
	InputStream is = Files.asByteSource(file).openStream();
	System.out.println("Guava Google InputStream is: "+is);		
	} catch (Exception e) {
	  e.printStackTrace();
	}
}

Output:
Guava Google InputStream is: [email protected]

Read a File using InputStream in Java

file to input stream in java

java file to inputstream

There are numerous ways to read the contents of a file using Java InputStream.

Using BufferReader readLine() method

Read streams of raw bytes using Java InputStream and decode them into characters using charset.

Here readLine() method read bytes from the file and convert into characters.

This method will read the InputStream line by line in Java.

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

	File file = new File("src/resources/hello.txt");
	String result = null;
	String line;	
	try {
	StringBuilder sb = new StringBuilder();
	InputStream in = new FileInputStream(file);
	BufferedReader br = new BufferedReader(new InputStreamReader(in));
	while ((line = br.readLine()) != null) {
		sb.append(line + System.lineSeparator());
	}
		result = sb.toString();	
		br.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
	System.out.println(result);
	}
}

Output:
Welcome

As the file “hello.txt” contains Welcome, it prints the same in the output above.

With Apache Commons IO package

Last but not the list to know how to convert file to an inputstream.

We can leverage the IOUtils class of Apache Commons IO library which will accept an InputStream

and displays the contents as a string using the specified content type.

The imports package for IOUtils is .apache.commons.io.IOUtils

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

		File file = new File("src/resources/hello.txt");
		String results;
		try (InputStream in = new FileInputStream(file)) {
			results = IOUtils.toString(in, StandardCharsets.UTF_8);
			System.out.println(results);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Output:
Welcome

Using InputStream read() method

Last but not the list in file to inputstream,

Here read() method reads a byte data from the InputStream.

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

		File file = new File("src/resources/hello.txt");
		int result;
		try (InputStream in = new FileInputStream(file)) {
			while ((result = in.read()) != -1) {
				System.out.print((char)result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Output:
Welcome

Tip:

Likewise, if you are looking to read a zip file, then use ZipInputStream to achieve it.

For reading large files like large CSV files, we can use Stream API from Java 8.

Also for parsing a CSV file, we can use Apache commons CSV library and BufferedReader.

To conclude this java tutorial, we covered various examples using different packages/libraries.

 

Interview FAQ

 

How to read InputStream line by line in Java?

We can use BufferedReader with FileInputStreamReader to read InputStream line by line.

BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream));
while(bufferReader.ready()) {
String line = bufferReader.readLine();
}

What is ByteArrayInputStream?

ByteArrayInputStream will read byte array as input stream.

This class consists an internal buffer which uses to read the byte array as a stream.

Also the ByteArrayInputStream buffer grows according to the data.

What is InputStreamReader?

InputStreamReader class translate bytes of an InputStream as text instead of numeric data.

Also we can set and get the character encoding using InputStreamReader.

You can set the character encoding using method Charset.forName(“UTF-8”).

InputStream inputStream = new FileInputStream(“sample.txt”);
InputStreamReader reader = new InputStreamReader(inputStream, Charset.forName(“UTF-8”));

Also you can get the character encoding using method getEncoding().

FileInputStream fileStream = new FileInputStream(“sample.txt”);
InputStreamReader reader = new InputStreamReader(fileStream);
String encoding = reader.getEncoding();

Best And Different Approaches How To Sort Arraylist In Java

Best And Different Approaches How To Sort Arraylist In Java

How to sort ArrayList in Java: Find the best solution for this in this article.

Let’s explore different approaches for sorting elements of an ArrayList in this post.

ArrayList is one of the widely used collection classes of the Collection Framework in Java.

ArrayList is nothing but a List implementation that implements a dynamic array to store the elements internally.

Thus, an ArrayList will dynamically grow and reduce as long as you add and remove elements.

How To Sort ArrayList in Java

ArrayList Is Widely used classes of the framework in Java. Let’s check out the best approaches to sort ArrayList in Java in every order Ascending order, Descending order, integer objects, and more. To sort the Arraylist in Java you need to call to collection.sort() methods.

You may like,

Whether Number or String is Palindrome in Java.

Sorting ArrayList of String Objects

Assume an ArrayList that holds State names as String Objects.

In order to sort the ArrayList, we need to call a method Collections.sort().

Here we need to pass the ArrayList object as an argument to the Collections.sort() method.

Note that, by default, this method returns the sorted list of String in ascending order alphabetically.

If You have any doubts about How to sort ArrayList in java, feel free to comment on us, we will definitely answer your doubt.

Sort String in Ascending Order

Let’s write the code to sort the ArrayList of String in Ascending order.

Let’s Initialize the ArrayList object in the constructor and add the states to the ArrayList.

Finally pass the Arraylist object to Collections.sort() method.

import java.util.ArrayList;
import java.util.Collections;

public class Main
{
 public static void main(String[] args) {

  try {
	  ArrayList stateList = new ArrayList<>();         
	  stateList.add("Florida");         
	  stateList.add("Illinois");         
	  stateList.add("Alabama");         
	  stateList.add("Texas");
	  Collections.sort(stateList);
	  System.out.println("Sorted Results : "+stateList);
	} catch (Exception e) {
	   e.printStackTrace();
	}
}
}

Output:
Sorted Results : [Alabama, Florida, Illinois, Texas]

Here the output above is in List of String format, you can also convert the List to String in Java as per the need.

Sort String in Descending Order

Let’s write the code to sort the ArrayList of String in Descending order.

Apart from passing the ArrayList object, here we also need to pass a Comparator argument.

So we will pass Collections.reverseOrder() as comparator in below code.

import java.util.ArrayList;
import java.util.Collections;

public class Main
{
 public static void main(String[] args) {

  try {
	  ArrayList stateList = new ArrayList<>();         
	  stateList.add("Florida");         
	  stateList.add("Illinois");         
	  stateList.add("Alabama");         
	  stateList.add("Texas");
	  Collections.sort(stateList,Collections.reverseOrder());
	  System.out.println("Sorted Results : "+stateList);
	} catch (Exception e) {
	   e.printStackTrace();
	}
}
}

Output:
Sorted Results : [Texas, Illinois, Florida, Alabama]

Sorting ArrayList of Integer Objects

sort arraylist in java

Sort ArrayList in Java

it’s one of more how to sort ArrayList in java by sorting Arraylist of integer objects.

Assume an ArrayList that holds numbers as Integer Objects.

In order to sort the ArrayList, we need to call a method Collections.sort().

Here we need to pass the ArrayList object as an argument to the Collections.sort() method.

Note that, by default, this method returns the sorted list of Integer in ascending order.

Sort Integer in Ascending Order

Let’s write the code to sort the ArrayList of Integer in Ascending order.

Let’s Initialize the ArrayList object in the constructor and add the numbers to the ArrayList.

Finally pass the Arraylist object to Collections.sort() method.

import java.util.ArrayList;
import java.util.Collections;

public class Main
{
 public static void main(String[] args) {

  try {
	 ArrayList numberList = new ArrayList<>();         
	 numberList.add(7);         
	 numberList.add(5);         
	 numberList.add(15);         
	 numberList.add(3);
	 Collections.sort(numberList);
	 System.out.println("Sorted Results : "+numberList);
   } catch (Exception e) {
	  e.printStackTrace();
   }
}
}

Output:
Sorted Results : [3, 5, 7, 15]

Sort Integer in Descending Order

Our last but not the least on how to sort ArrayList in java by the integer descending order.

Let’s write the code to sort the ArrayList of String in Descending order.

Apart from passing the ArrayList object, here we also need to pass a Comparator argument.

So we will pass Collections.reverseOrder() as comparator in below code.

import java.util.ArrayList;
import java.util.Collections;

public class Main
{
 public static void main(String[] args) {

  try {
	  ArrayList numberList = new ArrayList<>();         
	  numberList.add(7);         
	  numberList.add(5);         
	  numberList.add(15);         
	  numberList.add(3);
	  Collections.sort(numberList,Collections.reverseOrder());
	  System.out.println("Sorted Results : "+numberList);
    } catch (Exception e) {
	   e.printStackTrace();
	}
}
}

Output:
Sorted Results : [15, 7, 5, 3]

Conclusion

Above are some of the best approaches w.r.t how to sort ArrayList in java.

To conclude this tutorial, we covered various types of implementation to sort ArrayList in Java.

Palindrome Program In Java: Learn How To Check it a number or a string

Palindrome Program In Java: Learn How To Check it a number or a string

Looking to explore Palindrome in Java? Let’s discuss the details in this post.

Introduction to Palindrome In Java?

A palindrome is a phrase, number, digit, word, or sequence of characters which can read the same from backward as forward.

Let’s see some of the examples of the Palindrome algorithm.

Numeric Palindrome

Palindrome Numbers:

11, 121, 333, 5555

Palindrome Time:

12:21, 13:31, 11:11

Palindrome Words, Sentences, Names

1. Palindrome Words

rotor, civic, level, racecar

2. Palindrome Names

anna, eve, bob

3. Palindrome Sentences

was it a car or a cat i saw, mr owl ate my metal worm, do geese see god.

Using Java Implementation

Let’s write a Java Palindrome program to check whether the given number is Palindrome or not.

Here the input we provided in the below Java program is number 151(declared as integer variable).

In this case, we are using for loop logic for iteration.

We declared temp variable “actualValue”, to store the original string and compare it with reversed string.

Palindrome Number Validation

public static void main(String[] args) {

	try {
		int number = 151; 
		int reverseValue = 0;
		int reminder; 
		int actualValue;
		actualValue = number;
		for(;number!= 0; number /= 10)
	       {
	           reminder = number % 10;
	           reverseValue = reverseValue * 10 + reminder;
	       }
		if (actualValue == reverseValue)
			System.out.println(actualValue + " is a valid palindrome.");
		 else
			System.out.println(actualValue + " is not a valid palindrome.");
	} catch (Exception e) {
		e.printStackTrace();
	}
}

Output:
151 is a valid palindrome.

As per the above output step, we can see the original input number 151 is matching with reversed number 151 which results in invalid palindrome.

Let’s check the same implementation by using a while loop iteration in below Java program.

public static void main(String[] args) {

	try {
		int number = 151; 
		int reverseValue = 0;
		int reminder; 
        int actualValue;
		actualValue = number;
		while (number != 0) {
			reminder = number % 10;
			reverseValue = reverseValue * 10 + reminder;
			number /= 10;
		}
		if (actualValue == reverseValue)
			System.out.println(actualValue + " is a valid palindrome.");
		else
			System.out.println(actualValue + " is not a valid palindrome.");
	} catch (Exception e) {
		e.printStackTrace();
	}
}

Output:
151 is a valid palindrome.

As per the above output, the original number is matching with the reversed number.

In other words, it should be the same from first to the last digit and last to the first digit.

You May Like,

Palindrome String Validation

in this section, you will know palindrome string validation in palindrome in java.

Let’s write a Palindrome program to check whether the input string is Palindrome or not.

Here is an example.

public static void main(String[] args) {

	try {
		String inputValue = "rotor"; 
		String reverseValue = "";
		int length = inputValue.length();   
			for ( int x = length - 1; x >= 0; x-- )  
			 reverseValue = reverseValue + inputValue.charAt(x);  
		if (inputValue.equals(reverseValue))
			System.out.println(inputValue + " is a valid palindrome.");
		else
			System.out.println(inputValue + " is not a valid palindrome.");
	} catch (Exception e) {
		e.printStackTrace();
	}
}

Output:
rotor is a valid palindrome.

As per the above output, the input character is matching with the reversed character.

Palindrome Validation using Reverse Method

java palindrome

Palindrome java validation

in this section lets validate palindrome in java using the reverse method.

Let’s leverage the Java library method reverse() of StringBuffer.

Using the Palindrome program below, let’s use the reverse method to check whether the given string is Palindrome or not.

The program will compare the original string with the reversed string and delivers the result accordingly.

public static void main(String[] args) {

	try {
		String inputValue ="Ana";
		String reverseValue = new StringBuffer(inputValue).reverse().toString(); 		  
		if (inputValue.equalsIgnoreCase(reverseValue)) 		      
		    System.out.println(inputValue + " is a valid palindrome.");		  
		   else
			System.out.println(inputValue + " is not a valid palindrome.");
	} catch (Exception e) {
		e.printStackTrace();
	}
}

Output:
Ana is a valid palindrome.

As per the output above, we can see the input is matching with reverse order or reverse string and thus results in invalid Palindrome.

To conclude this tutorial, we covered various types of solution to validate Palindrome in Java.

Write String to a File in Java

Write String to a File in Java

Looking to Write String to File Java? Lets explore different ways to achieve it.

Using BufferedWriter

Let’s use BufferedWriter of Java to write a String to a new text file.

public static void main(String[] args) throws IOException {
try {
	 String value = "Welcome";
	 BufferedWriter bw = new BufferedWriter(new FileWriter("src/resources/hello.txt"));
	 bw.write(value);
	 bw.close();
	 System.out.println("Output written to hello.txt is: " +value);		 
	} catch (Exception e) {
		 e.printStackTrace();
	}

}

Output:
Output written to hello.txt is: Welcome

 

With FileOutputStream

Let’s use FileOutputStream class to write binary data to a text file.

Below code converts a String byte array and writes the bytes to a file using FileOutputStream.

The file path is passed to the output stream to write the desired string value as per the program.

public static void main(String[] args) throws IOException {
 try {
	  String value = "Welcome";
	  FileOutputStream fos = new FileOutputStream("src/resources/hello.txt");
	  byte[] bytes = value.getBytes();
	  fos.write(bytes);
	  fos.close();
	  System.out.println("Output written to hello.txt is: " +value);		 
	} catch (Exception e) {
		e.printStackTrace();
	}

}
Output:
Output written to hello.txt is: Welcome

 

Using PrintWriter

We can use PrintWriter object to write formatted text to a file.

First the file path is passed to the FileWriter class.

And then PrintWriter class will process the Java FileWriter to print the formatted text in a file.

public static void main(String[] args) throws IOException {
 try {
	 FileWriter fileWriter = new FileWriter("src/resources/hello.txt");
	 PrintWriter pw = new PrintWriter(fileWriter);
	 pw.printf("Welcome to %s in Year %d", "Java World", 2020);
	 pw.close();
	} catch (Exception e) {
		e.printStackTrace();
	}

}

Output:
Output written to hello.txt is below

Welcome to Java World in Year 2020

 

With DataOutputStream

Let’s leverage DataOutputStream to write a String to a file.

Also the writeUTF method takes care of character encoding format that has to be written to a file.

The default character encoding is modified UTF-8 format.

public static void main(String[] args) throws IOException {
 try {
	 String value = "Welcome";
	 FileOutputStream fs = new FileOutputStream("src/resources/hello.txt");
	 DataOutputStream os = new DataOutputStream(new BufferedOutputStream(fs));
	 os.writeUTF(value);
	 os.close();
	 System.out.println("Output written to hello.txt is: " +value);
	} catch (Exception e) {
		e.printStackTrace();
	}

}

Output:
Output written to hello.txt is: Welcome

 

Using FileChannel

Let’s use FileChannel to write a String to a file.

Also FileChannel will be faster than the traditional Java IO.

public static void main(String[] args) throws IOException {
 try {
	RandomAccessFile stream = new RandomAccessFile("src/resources/hello.txt", "rw");
	FileChannel channel = stream.getChannel();
	String value = "Welcome";
	byte[] strBytes = value.getBytes();
	ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
	buffer.put(strBytes);
	buffer.flip();
	channel.write(buffer);
	stream.close();
	channel.close();
	System.out.println("Output written to hello.txt is: " +value);
 } catch (Exception e) {
	e.printStackTrace();
	}

}

Output:
Output written to hello.txt is: Welcome

 

Create and Write to a Temporary File

Let’s create a temporary file using createTempFile method from File Object.

And then to write a String to a file, lets use Java FileWriter class.

public static void main(String[] args) throws IOException {
 try {
	String value = "Welcome";
	File tempFile = File.createTempFile("testfile", ".tmp");
	FileWriter writer = new FileWriter(tempFile);
	writer.write(value);
	writer.close();
  } catch (Exception e) {
	e.printStackTrace();
  }

}

Output:
The testfile.tmp will be created in Temp folder and the value 'Welcome' written to the temp file.

 

To conclude this java tutorial, we covered various examples to write string to a file in Java.

Happy Coding Readers 🙂

Convert Java Char Array to a String

Convert Java Char Array to a String

Looking to convert Java Char array to String?

Lets explore numbers of ways to achieve it using Java programming language.

Char array can be converted to String and vice versa.

Allocate a String that exhibits the sequence of characters present in a char array.

As String is immutable in Java, the consecutive modification of the character array does not impact the allocated String.

Using String Constructor

The String class provides inbuilt constructor which accepts a char array as an argument.

public static void main(String[] args) {
	try {
	 char[] charArray = { 'W', 'E', 'L', 'C', 'O', 'M', 'E'};
	 String value = new String(charArray);
	 System.out.println("String Class Value is: " +value);		 
	} catch (Exception e) {
		e.printStackTrace();
	}

}

Output:
String Class Value is: WELCOME

 

With StringBuilder

public static void main(String[] args) {
try {
  final char[][] arrayCharArray = {{'w','e'},{'l','c'},{'o','m','e'}};    
  StringBuilder sb = new StringBuilder();
  for (char[] childArray : arrayCharArray) {
   sb.append(childArray);
    }
    System.out.println("After Forming as String: " +sb);		 
    } catch (Exception e) {
		e.printStackTrace();
    }

}

Output:
After Forming as String: welcome

 

Using String.valueOf() Method

The String class provides valueOf() method which converts to string directly.

public static void main(String[] args) {
 try {
   char[] charArray = { 'W', 'E', 'L', 'C', 'O', 'M', 'E'};
   String value = String.valueOf(charArray);
   System.out.println("String Value is: " +value);		 
     } catch (Exception e) {
	   e.printStackTrace();
     }

}

Output:
String Value is: WELCOME

 

Using String.copyValueOf() Method

The String class provides another method copyValueOf() method.

This will copy char array to string in Java.

This method is very similar to valueOf() method.

public static void main(String[] args) {
try {
  char[] charArray = { 'W', 'E', 'L', 'C', 'O', 'M', 'E'};
  String value = String.copyValueOf(charArray);
  System.out.println("String copyValueOf is: " +value);		 
    } catch (Exception e) {
       e.printStackTrace();
    }

}

Output:
String copyValueOf is: WELCOME

 

Utilizing Java 8 Streams

We can utilize the Collectors.joining() method to form a String.

stream method defined in the following way.

public static void main(String[] args) {
try {
  Character[] charArray = { 'W', 'E', 'L', 'C', 'O', 'M', 'E'};
  Stream<Character> charStream = Arrays.stream(charArray);
  String value = charStream.map(String::valueOf).collect(Collectors.joining());	    
  System.out.println("String Java 8 Stream is: " +value);		 
    } catch (Exception e) {
	   e.printStackTrace();
    }

}

Output:
String Java 8 Stream is: WELCOME

 

Using Google’s Guava Joiner Method

We can use the Guava Common Base Joiner method, to convert from Character array to delimiter string value.

The import package is import com.google.common.base.Joiner;

public static void main(String[] args) {
 try {
	Character[] charArray = { 'W', 'E', 'L', 'C', 'O', 'M', 'E'};
	String value = Joiner.on("-").join(charArray);
	System.out.println("Joiner Value is: " +value);		 
     } catch (Exception e) {
        e.printStackTrace();
     }

}

Output:
Joiner Value is: W-E-L-C-O-M-E

 

Convert a Byte Array to String in Java

As we know byte[] stores binary data and String stores text data.

So lets see how to convert a byte array to string with character encoding and without character encoding.

With Character Encoding:

It supports both UNICODE and ASCII format.

In this case, lets use StandardCharsets.UTF_8 to specify the type of character encoding type.

This tells how to encode the input characters into the sequence of bytes.

public static void main(String[] args) throws IOException
	{
		String value = "Byte Array";
		byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
		// Now Create a string from a byte array with "UTF-8" encoding
		String result = new String(bytes, StandardCharsets.UTF_8);
		System.out.println(result);
	}
	

Output:	
Byte Array

Without Character Encoding:

Lets convert byte array to string without specifying the character encoding.

So here we declared an string variable and converted into bytes using getBytes() method.

Finally passed the bytes to String object instance to achieve the desired output.

public static void main(String[] args) throws IOException
	{
		String value = "Byte Array";
		byte[] bytes = value.getBytes();
		String result = new String(bytes);
		System.out.println(result);
	}
	

Output:	
Byte Array


You May Also Love,

Iterate through the characters of a string in Java

Lets use for loop function to iterate the number of characters of a String.

Apply charAt() method to retrieve each character and check it.

public static void main(String[] args) throws IOException
	{
		String value = "char";
		for (int i = 0; i < value.length(); i++){
		    char result = value.charAt(i);
		    System.out.println("printing : "+result);
		}

	}
	

Output:	
printing : c
printing : h
printing : a
printing : r

Lets look at efficient way of using for loop function with below code snippet.

public static void main(String[] args) throws IOException
	{
		String value = "char";
		for(char result : value.toCharArray()) {
			System.out.println("printing : "+result);
		}
	}	

Output:
printing : c
printing : h
printing : a
printing : r



Tip:
Unlike C, There’s no such entity as NULL in Java. Null is not a valid value for a char variable.
A char can have a integer value of zero, which has no particular significance.

To conclude this java tutorial, we covered various examples on converting char Array to a String in Java.

Convert Java File to InputStream | Tracedynamics

Java File To Inputstream: Know How To Convert InputStream From File

Looking to convert Java InputStream from File?

Let’s look at some of the Java InputStream examples in this tutorial.

Let’s convert a File to an InputStream in numerous ways of implementation.

What is InputStream?

InputStream is an abstract class of Java API.

Its a superclass of all classes defining an input stream of bytes.

InputStream extends Object and its implemented Interfaces are Closeable, AutoCloseable.

InputStream Subclasses are AudioInputStream, ByteArrayInputStream, FileInputStream, FilterInputStream, InputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream.

These are particularly helpful for reading and write operations on file streams or input files.

Again let’s go in detail about first, second, third ways of converting File to InputStream.

Convert using Traditional Java IO Package

Our first method to convert Java File To Inputstream.

In the first place, let’s leverage the Java IO package to convert a File format to different InputStream’s.

Of course under the IO package, the first one we use is FileInputStream.

Following Java code read a file from the file path/folder directory location.

Furthermore it converts into InputStream using method FileInputStream().

public static void main(String[] args) throws IOException {
	try {
		File file = new File("src/resources/hello.txt");
		InputStream is = new FileInputStream(file);
		System.out.println("InputStream is: " + is);
        is.close();
	} catch (Exception e) {
			e.printStackTrace();
	}
}

Output:
InputStream is: [email protected]

As per output, the program reads a txt file and converts a File to an InputStream.

of course, next is by using SequenceInputStream.

Java program concatenates the input data stream of two files to a single InputStream.

public static void main(String[] args) throws IOException {
try {
	File file = new File("src/resources/Hello.txt");
	File file2 = new File("src/resources/Test.txt");
	InputStream firstIS = new FileInputStream(file);
	InputStream secondIS = new FileInputStream(file2);
	InputStream is = new SequenceInputStream(firstIS, secondIS);
	System.out.println("SequenceInputStream is: "+is);
    firstIS.close();
	secondIS.close();
	is.close();
    } catch (Exception e) {
	  e.printStackTrace();
	}
}

Output:
SequenceInputStream is: [email protected]

Not to mention, finally using DataInputStream.

This will read primitive data stream or binary data from a file.

public static void main(String[] args) throws IOException {
try {
	 File file = new File("src/resources/Hello.txt");
 	 InputStream is = new DataInputStream(new FileInputStream(file));
  	 System.out.println("DataInputStream is: "+is);	
     is.close();
	 } catch (Exception e) {
	  e.printStackTrace();
	}
}

Output:
DataInputStream is: [email protected]

These just for you,

File to InputStream using Java 8

Using Java 8 method to convert Java File To Inputstream.

Using Java 8, we can save the input stream to file as below

public static void main(String[] args) throws IOException {
		String TARGET_PATH = "C:\\test\\wikipedia.txt";
	try {
		URI uri = URI.create("https://www.wikipedia.com/");
		InputStream inputStream = uri.toURL().openStream();
		Files.copy(inputStream, Paths.get(TARGET_PATH),StandardCopyOption.REPLACE_EXISTING);
		System.out.println("File copied to location: " + TARGET_PATH);
	} catch (Exception e) {
		e.printStackTrace();
	}

}

Output:
File copied to location: C:\test\wikipedia.txt

By using Apache Commons IO Library

file to input stream in java

java file to inputstream

Using Apache Commons IO Library API, we can convert File to an InputStream as below.

public static void main(String[] args) throws IOException {
try {
	File file = new File("src/resources/Hello.txt");
	InputStream is = FileUtils.openInputStream(file);
	System.out.println("Apache Commons InputStream is: "+is);		
	} catch (Exception e) {
	  e.printStackTrace();
	}
}

Output:
Apache Commons InputStream is: [email protected]

Apache Commons IO library can be download from here.

Java File to InputStream using Guava Library

It is my favorite, using Guava Library converts Java File To Inputstream.

As we know Guava is an open-source Java API library from Google.

Using Guava we can convert File to an InputStream with below source code.

public static void main(String[] args) throws IOException {
try {
	File file = new File("src/resources/Hello.txt");
	InputStream is = Files.asByteSource(file).openStream();
	System.out.println("Guava Google InputStream is: "+is);		
	} catch (Exception e) {
	  e.printStackTrace();
	}
}

Output:
Guava Google InputStream is: [email protected]

Read a File using InputStream in Java

There are numerous ways to read the contents of a file using Java InputStream.

Using BufferReader readLine() method

Read streams of raw bytes using Java InputStream and decode them into characters using charset.

Here readLine() method read bytes from the file and convert into characters.

This method will read the InputStream line by line in Java.

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

	File file = new File("src/resources/hello.txt");
	String result = null;
	String line;	
	try {
	StringBuilder sb = new StringBuilder();
	InputStream in = new FileInputStream(file);
	BufferedReader br = new BufferedReader(new InputStreamReader(in));
	while ((line = br.readLine()) != null) {
		sb.append(line + System.lineSeparator());
	}
		result = sb.toString();	
		br.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
	System.out.println(result);
	}
}

Output:
Welcome

As the file “hello.txt” contains Welcome, it prints the same in the output above.

With Apache Commons IO package

We can leverage IOUtils class of Apache Commons IO library which will accept an InputStream,

and displays the contents as a string using the specified content type.

the import package for IOUtils is .apache.commons.io.IOUtils

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

		File file = new File("src/resources/hello.txt");
		String results;
		try (InputStream in = new FileInputStream(file)) {
			results = IOUtils.toString(in, StandardCharsets.UTF_8);
			System.out.println(results);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Output:
Welcome

Using InputStream read() method

Here read() method reads a byte data from the InputStream.

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

		File file = new File("src/resources/hello.txt");
		int result;
		try (InputStream in = new FileInputStream(file)) {
			while ((result = in.read()) != -1) {
				System.out.print((char)result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Output:
Welcome

Tip:

Likewise, if you are looking to read a zip file, then use ZipInputStream to achieve it.

For reading large files like large CSV files, we can use Stream API from Java 8.

Also for parsing a CSV file, we can use Apache commons CSV library and BufferedReader.

To conclude this java tutorial, we covered various examples using different packages/libraries.

 

Interview FAQ

 

How to read InputStream line by line in Java?

We can use BufferedReader with FileInputStreamReader to read InputStream line by line.

BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream));
while(bufferReader.ready()) {
String line = bufferReader.readLine();
}

What is ByteArrayInputStream?

ByteArrayInputStream will read byte array as input stream.

This class consists an internal buffer which uses to read the byte array as a stream.

Also the ByteArrayInputStream buffer grows according to the data.

What is InputStreamReader?

InputStreamReader class translate bytes of an InputStream as text instead of numeric data.

Also we can set and get the character encoding using InputStreamReader.

You can set the character encoding using method Charset.forName(“UTF-8”).

InputStream inputStream = new FileInputStream(“sample.txt”);
InputStreamReader reader = new InputStreamReader(inputStream, Charset.forName(“UTF-8”));

Also you can get the character encoding using method getEncoding().

FileInputStream fileStream = new FileInputStream(“sample.txt”);
InputStreamReader reader = new InputStreamReader(fileStream);
String encoding = reader.getEncoding();

Pin It on Pinterest