在我的 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/