public class Demo05 {
public static void main(String[] args) throws IOException {
File fi = new File("c:\\stu.txt");
String s = readTxt(fi); //尽量保证输出操作由顾客控制.因此返回字符串.
System.out.println(s);
}
//接受一个文件,将文件数据封装成字符串,并返回.
public static String readTxt(File fi) throws IOException {
FileInputStream fs = new FileInputStream(fi);
byte[] by = new byte[5];
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int i =0;
while((i = fs.read(by))!= -1)
{
bs.write(by,0,i); //不管读到哪里,因为bs都只是接受的,所以循环到-1停止,再一次转成字符串就好了.
}
return bs.toString();
}
}
|
|