How to convert a String to an InputStream in Java

3 Answers

0 votes
import java.io.InputStream;
import java.io.ByteArrayInputStream;

public class MyClass {
    public static void main(String args[]) throws Exception {
        String s = "Java programming language";
        
        InputStream input = new ByteArrayInputStream(s.getBytes("UTF-8")); 
         
        int i;
        while ((i = input.read()) > -1) {
            System.out.print((char) i);
        }
    }
}
 
 
 
/*
run:
 
Java programming language
 
*/

 



answered Jun 29, 2020 by avibootz
edited May 19, 2024 by avibootz
0 votes
import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;

public class MyClass {
    public static void main(String args[]) throws IOException {
        String str = "Java c c++ c# python";
         
        InputStream istream = new ByteArrayInputStream(str.getBytes());
         
        String istreamtext = new BufferedReader(
                            new InputStreamReader(istream, StandardCharsets.UTF_8))
                            .lines()
                            .collect(Collectors.joining("\n"));
 
        System.out.println(istreamtext);
    }
}
  
  
  
   
/*
run:
      
Java c c++ c# python
    
*/

 



answered May 19, 2024 by avibootz
0 votes
import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;

public class MyClass {
    public static void main(String args[]) throws IOException {
        String str = "Java c c++ c# python go";
         
        InputStream istream = new ByteArrayInputStream(str.getBytes("UTF-8"));
         
        String istreamtext = new BufferedReader(
                            new InputStreamReader(istream, StandardCharsets.UTF_8))
                            .lines()
                            .collect(Collectors.joining("\n"));
 
        System.out.println(istreamtext);
    }
}
  
  
  
   
/*
run:
 
Java c c++ c# python go
 
*/

 



answered May 19, 2024 by avibootz

Related questions

3 answers 348 views
2 answers 240 views
1 answer 219 views
1 answer 190 views
1 answer 268 views
1 answer 173 views
...