在我的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 - 如何在Java中将FileInputStream转换为字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15161553/