黑马程序员技术交流社区

标题: 定义一个文件输入流,调用read(byte[] b)方法将exercise.txt... [打印本页]

作者: 就是喜欢安卓    时间: 2015-6-4 14:58
标题: 定义一个文件输入流,调用read(byte[] b)方法将exercise.txt...
我的入学测试有一题,“定义一个文件输入流,调用read(byte[] b)方法将exercise.txt文件中的所有内容打印出来(byte数组的大小限制为5)”。
下面代码正确吗?请各位大神指教。我这题没说不考虑中文编码问题。
public class Test8 {

public void test8() {
  FileInputStream fis = null;
  try {
   // 创建文件输入流对象
   fis = new FileInputStream(new File(
     "exercise.txt"));
   byte buffer[] = new byte[5];
   // 读取输入流
   while ((fis.read(buffer, 0, buffer.length) != -1)){
    System.out.print(new String(buffer));
   }
   System.out.println("");

  } catch (IOException ioe) {
   ioe.getStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   //关闭流
   try {
    if(fis!=null){
     fis.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
}
}


作者: wangkai    时间: 2015-6-4 17:02
你定义个文件看有乱码没
作者: 就是喜欢安卓    时间: 2015-6-4 19:58
wangkai 发表于 2015-6-4 17:02
你定义个文件看有乱码没

测试了,中文会乱码。编码改成UTF-8后,注释里的题目直接乱码了。
作者: win_rainbow    时间: 2015-6-4 21:52
这样写输出中文肯定会乱码,因为中文是两个字节表示,只就使用ByteArrayOutputStream,将字节缓存后统一输出,try中代码修改如下:
  1. try
  2.                 {
  3.                         fis = new FileInputStream(new File("exercise.txt"));
  4.                         ByteArrayOutputStream bos = new ByteArrayOutputStream ();
  5.                         byte [] buffer = new byte[5];
  6.                         while (fis.read(buffer,0,buffer.length)!=-1)
  7.                         {
  8.                                 bos.write(buffer, 0, 5);
  9.                                 }
  10.                         System.out.println(bos.toString());
  11.                         }
复制代码






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2