使用java.util.Scanner
类,可以将InputStream
转换为String。 以下是将InputStream
转换为String的示例。
代码文件:InputStreamToStringExample.java –
package com.yiibai.tutorial.io; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Scanner; /** * @author yiibai */ public class InputStreamToStringExample { public static void main(String[] args) { File file=new File("file.txt"); FileInputStream fileInputStream=null; try { fileInputStream=new FileInputStream(file); String text=InputStreamToStringExample.streamToString(fileInputStream); System.out.println(text); } catch (Exception e) { e.printStackTrace(); } } private static String streamToString(InputStream inputStream){ @SuppressWarnings("resource") Scanner scanner=new Scanner(inputStream).useDelimiter("/A"); try { return scanner.next(); } finally { scanner.close(); } } }
执行上面示例代码,得到以下结果:
This is an example of converting InputStream to String.
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264096.html