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

标签 java fileinputstream

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

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

最佳答案

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

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

关于java - 如何在java中将FileInputStream转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15161553/

相关文章:

java - 如何从 Tomcat url 中删除端口号?

java - java中的枚举值列表

java - unicode支持java和mysql

Java - 访问 ValueMap 时遇到问题

java - 将数组传递给绘画组件类?

c++ - 在C++上接收 “Error: expected an identifier”的 “==”

java - 读取(字节[] b,int关闭,int len): Reading A File To Its End

java - 除非我调用 os.close(),否则不会收到文件

java - 无法合并两个 mp3 文件

java - 读取文件 java.io 时出错