如何在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());
使用Aubin的解决方案:
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转换为字符串? 的全部内容, 来源链接: utcz.com/qa/432044.html