How to convert ByteBuffer to String in Java

2 Answers

0 votes
import java.nio.ByteBuffer;
import java.io.UnsupportedEncodingException;
 
public class MyClass {
    public static void main(String args[]) throws UnsupportedEncodingException  {
        String s = "Java is a high-level, class-based, object-oriented programming language";
         
        ByteBuffer byteBuffer = ByteBuffer.wrap(s.getBytes("UTF-8"));
        
        String converted = new String(byteBuffer.array(), "UTF-8");
         
        System.out.println(converted);
    }
}
 
 
 
 
/*
run:
 
Java is a high-level, class-based, object-oriented programming language
 
*/

 



answered Nov 6, 2021 by avibootz
edited Oct 11, 2023 by avibootz
0 votes
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.ByteBuffer;

public class MyClass {
    public static void main(String args[]) throws UnsupportedEncodingException {
        String str = "Java object-oriented programming language";

        ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes("UTF-8"));
       
        String converted = StandardCharsets.UTF_8.decode(byteBuffer).toString();

        System.out.println(converted);
    }
}
  

  
  
  
/*
run:
  
Java object-oriented programming language
  
*/

 



answered Oct 11, 2023 by avibootz

Related questions

1 answer 142 views
1 answer 163 views
1 answer 107 views
107 views asked Jun 6, 2023 by avibootz
3 answers 216 views
216 views asked Nov 6, 2021 by avibootz
1 answer 131 views
131 views asked Nov 6, 2021 by avibootz
...