本文介绍了如何在Java中将FileInputStream转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Java项目中,我将FileInputStream传递给一个函数,我需要转换(将类型转换FileInputStream转换为字符串),怎么做.

In my java project, I'm passing FileInputStream to a function,I need to convert (typecast FileInputStream to string),How to do it.??

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

推荐答案

您不能直接将其转换为字符串.你应该实现这样的事情将此代码添加到您的方法中

You can't directly convert it to string. You should implement something like thisAdd this code to your method

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

使用Aubin解决方案:

Use Aubin's solution:

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

这篇关于如何在Java中将FileInputStream转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-21 02:46