InputStream to String

Setup

private static final String FILE_PATH = "com/levelup/java/io/inputstream-to-string.txt";
private URI fileLocation;

@Before
public void setUp() throws URISyntaxException {
    fileLocation = this.getClass().getClassLoader().getResource(FILE_PATH).toURI();
}

File contents

Inputstream to string

Straight up Java

FileInputStream

@Test
public void convert_inputstream_to_string_java () throws IOException {
    
    File file = new File(fileLocation);

    InputStream inputStream = new FileInputStream(file);
    
    StringBuilder fileContent = new StringBuilder();

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(inputStream, Charsets.UTF_8));
    
    String line = bufferedReader.readLine();
    while (line != null){
        fileContent.append(line);
        line = bufferedReader.readLine();
    }
    
    bufferedReader.close();
    
    assertEquals("Inputstream to string", fileContent.toString());
}

Scanner

@Test
public void convert_inputstream_to_string_java_scanner () throws FileNotFoundException {

    File file = new File(fileLocation);

    InputStream inputStream = new FileInputStream(file);

    Scanner scanner = new Scanner(inputStream);

    //only read first line
    String fileContent = scanner.nextLine();
    
    scanner.close();
    
    assertEquals("Inputstream to string", fileContent);
}

Google Guava

@Test
public void convert_inputstream_to_string_guava () throws IOException {

    File file = new File(fileLocation);
    
    InputStream inputStream = new FileInputStream(file);
    
    String fileContent = CharStreams.toString(
            new InputStreamReader(inputStream, Charsets.UTF_8));
    
    Closeables.close(inputStream, false);
    
    assertEquals("Inputstream to string", fileContent);
}

Apache Commons

@Test
public void convert_inputstream_to_string_apache () throws IOException {

    File file = new File(fileLocation);
    InputStream inputStream = new FileInputStream(file);
    
    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, Charsets.UTF_8);
    String fileContent = writer.toString();
    
    assertEquals("Inputstream to string", fileContent);
}