如何在java中将FileInputStream转换为字符串?

bhu*_*n23 23 java fileinputstream

在我的java项目中,我将FileInputStream传递给一个函数,我需要将其转换(类型转换为FileInputStream为string),如何做到这一点.

public static void checkfor(FileInputStream fis) {
   String a=new String;
   a=fis         //how to do convert fileInputStream into string
   print string here
}
Run Code Online (Sandbox Code Playgroud)

Ars*_*yan 28

您无法直接将其转换为字符串.您应该实现类似这样的代码将此代码添加到您的方法中

    //Commented this out because this is not the efficient way to achieve that
    //StringBuilder builder = new StringBuilder();
    //int ch;
    //while((ch = fis.read()) != -1){
    //  builder.append((char)ch);
    //}
    //          
    //System.out.println(builder.toString());
Run Code Online (Sandbox Code Playgroud)

使用Aubin的解决方案:

public static String getFileContent(
   FileInputStream fis,
   String          encoding ) throws IOException
 {
   try( BufferedReader br =
           new BufferedReader( new InputStreamReader(fis, encoding )))
   {
      StringBuilder sb = new StringBuilder();
      String line;
      while(( line = br.readLine()) != null ) {
         sb.append( line );
         sb.append( '\n' );
      }
      return sb.toString();
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 按字符读取字符串效率不高. (2认同)

Aub*_*bin 20

public static String getFileContent(
   FileInputStream fis,
   String          encoding ) throws IOException
 {
   try( BufferedReader br =
           new BufferedReader( new InputStreamReader(fis, encoding )))
   {
      StringBuilder sb = new StringBuilder();
      String line;
      while(( line = br.readLine()) != null ) {
         sb.append( line );
         sb.append( '\n' );
      }
      return sb.toString();
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 您需要指定字符编码.您不能假设平台默认编码是正确的. (2认同)

atr*_*atr 8

使用Apache Commons IOUtils函数

import org.apache.commons.io.IOUtils;

InputStream inStream = new FileInputStream("filename.txt");
String body = IOUtils.toString(inStream, StandardCharsets.UTF_8.name()); 
Run Code Online (Sandbox Code Playgroud)