@Testpublicvoidconvert_inputstream_to_string_java()throwsIOException{Filefile=newFile(fileLocation);InputStreaminputStream=newFileInputStream(file);StringBuilderfileContent=newStringBuilder();BufferedReaderbufferedReader=newBufferedReader(newInputStreamReader(inputStream,Charsets.UTF_8));Stringline=bufferedReader.readLine();while(line!=null){fileContent.append(line);line=bufferedReader.readLine();}bufferedReader.close();assertEquals("Inputstream to string",fileContent.toString());}
Scanner
@Testpublicvoidconvert_inputstream_to_string_java_scanner()throwsFileNotFoundException{Filefile=newFile(fileLocation);InputStreaminputStream=newFileInputStream(file);Scannerscanner=newScanner(inputStream);//only read first lineStringfileContent=scanner.nextLine();scanner.close();assertEquals("Inputstream to string",fileContent);}
Google Guava
@Testpublicvoidconvert_inputstream_to_string_guava()throwsIOException{Filefile=newFile(fileLocation);InputStreaminputStream=newFileInputStream(file);StringfileContent=CharStreams.toString(newInputStreamReader(inputStream,Charsets.UTF_8));Closeables.close(inputStream,false);assertEquals("Inputstream to string",fileContent);}
Apache Commons
@Testpublicvoidconvert_inputstream_to_string_apache()throwsIOException{Filefile=newFile(fileLocation);InputStreaminputStream=newFileInputStream(file);StringWriterwriter=newStringWriter();IOUtils.copy(inputStream,writer,Charsets.UTF_8);StringfileContent=writer.toString();assertEquals("Inputstream to string",fileContent);}