如何将FileInputStream转换为Java中的字符串?

2022-09-01 13:43:01

在我的java项目中,我将FileInputStream传递给一个函数,我需要转换(typecast FileInputStream到字符串),如何做到这一点?

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

答案 1

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

    //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());

使用奥宾的解决方案:

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();
   }
}

答案 2
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();
   }
}

推荐