如何在Java中将FileInputStream转换为字符串? [英] How to convert FileInputStream into string in java?

查看:440
本文介绍了如何在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 this Add 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转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆