A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 小蚊子 中级黑马   /  2013-12-24 23:03  /  1544 人查看  /  3 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. package com;

  2. import java.io.File;
  3. import java.io.FileInputStream;

  4. public class Test8 {
  5.         public static void main(String[] args) {
  6.                 FileInputStream fis = null;
  7.                 try {
  8.                         File file = new File("bin/exercise.txt");
  9.                         fis = new FileInputStream(file);
  10.                         byte[] b = new byte[(int) file.length()];
  11.                         while (fis.read(b) != -1) {
  12.                         }
  13.                         System.out.println(new String(b));
  14.                 } catch (Exception e) {
  15.                         e.printStackTrace();
  16.                 }
  17.         }
  18. }
复制代码

定义一个文件输入流,调用read(byte[] b)方法将exercise.txt文件中的所有内容打印出来(byte数组的大小限制为5)。请问应该怎样实现?

评分

参与人数 1黑马币 +3 收起 理由
FFF + 3 淡定

查看全部评分

3 个回复

正序浏览

这段代码有毕老师的风格。
回复 使用道具 举报
  1. /*
  2. 需求:定义一个文件输入流,调用read(byte[] b)方法
  3. 将exercise.txt文件中的所有内容打印出来(byte数组的大小限制为5)

  4. 思路:如果5个字节一取,那么就说明可能出现乱码的情况
  5. 那么,可以使用ByteArrayOutputStream来把自己写到内存中,然后再写出去
  6. */
  7. import java.io.*;
  8. class Test {
  9.         public static void main(String[] args){
  10.                
  11.                 InputStream bais =null;
  12.                 try{
  13.                         bais = new FileInputStream(new File("C:\\Users\\sky\\Desktop\\exercise.txt"));
  14.                         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  15.                         byte[] by = new byte[5];
  16.                         int len = 0;
  17.                         while((len=bais.read(by)) != -1){
  18.                                 baos.write(by,0,len);
  19.                         }
  20.                         System.out.println(baos.toString());
  21.                 }catch(IOException e){
  22.                         System.out.println("读写异常");
  23.                 }finally{
  24.                         try{
  25.                                 if(bais != null)
  26.                                 bais.close();
  27.                         }catch(IOException e){
  28.                                 System.out.println("关闭异常");
  29.                         }               
  30.                 }
  31.         }
  32. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
FFF + 1 赞一个!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马