Avatar ·

How to read an InputStream and convert it to a string in Java?

Hello everyone! I'm a beginner in Java and I've encountered the following task: I have an `InputStream` object that I get, for example, when reading a file or from a network request. I need to convert the contents of this stream into a regular `String` so that I can process the text later. The problem is that I don't know how to do this correctly. I tried reading bytes manually, but the code turns out to be cumbersome and probably incorrect. Here's what I tried: ```java InputStream inputStream = new FileInputStream("file.txt"); StringBuilder sb = new StringBuilder(); int data = inputStream.read(); while (data != -1) { sb.append((char) data); data = inputStream.read(); } inputStream.close(); String result = sb.toString(); ``` This code works, but I'm sure there are more elegant solutions. I'm