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(); }
Inputstream to string
@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()); }
@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); }
@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); }
@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); }