Java基础知识字节流练习

Java基础知识字节流练习
读入文件时可以使用read(),或者使用read(byte[] buf)
写一个类使用read()模拟read(byte[] buf)

import java.io.File;
import java.io.FileInputStream;

/**
 *
 * @author steven
 */
public class IOtest02 {
    public static void main(String[] args) throws Exception {
        File fileNmae = new File("C:\\test\\1.txt");
        MyRead mr = new MyRead(fileNmae);
        byte[] buf = new byte[50];
        int len = mr.read(buf);
        while(len != -1){
            System.out.println(new String(buf,0,len));
            len = mr.read(buf);
            if(len<buf.length){//由于最后一个分数组没有装满,则len一定会小于分数组的长度
                do { //使用一次循环结构,do...false 直接输出最后一个数组的内容;                   
                System.out.println(new String(buf,0,len));
                len = -1;
                } while (false);
                
            }
        }
        
    }
}
class MyRead{
    File fileName;
    FileInputStream fis;
    public MyRead(File fileName) throws Exception{
        this.fileName = fileName;
         fis = new FileInputStream(fileName);
    }
    
    public int read(byte[] buf) throws Exception{
        int blen = buf.length;
        int len = 0 ;
       while(blen-- > 0){//除了最后一个数组每个分数组都能装满
           buf[len] = (byte) fis.read();
           if( buf[len] == -1){//最后一个分数组装不满,使用break停止
               break;
           }
           len++;
       }
        return len;
       }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我会尽力回答你的问题。首先,让我们来看一下节数据的输入输出基础知识。 在Java中,我们可以使用InputStream和OutputStream类来处理节数据的输入输出。其中,InputStream是一个抽象类,表示输入节流的基本类。OutputStream同样是一个抽象类,表示输出节流的基本类。这两个类都是Java IO库中的基本类,它们提供了一系列的方法来处理节数据的输入输出。 下面是一个简单的例子,演示如何使用InputStream和OutputStream类来读取和写入节数据: ```java import java.io.*; public class ByteIOExample { public static void main(String[] args) { byte[] data = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33}; // 写入节数据到文件 try (OutputStream output = new FileOutputStream("hello.txt")) { output.write(data); } catch (IOException e) { e.printStackTrace(); } // 从文件中读取节数据 try (InputStream input = new FileInputStream("hello.txt")) { byte[] buffer = new byte[1024]; int length = input.read(buffer); String message = new String(buffer, 0, length); System.out.println(message); } catch (IOException e) { e.printStackTrace(); } } } ``` 在这个例子中,我们首先创建了一个byte数组,表示要写入文件的数据。然后,使用OutputStream类将数据写入到名为"hello.txt"的文件中。接着,使用InputStream类从文件中读取数据,并将其存储在一个byte数组中。最后,将这个byte数组转换成符串并打印出来。 希望这个例子能够帮助你更好地理解节数据的输入输出。如果你有任何其他问题,可以继续问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值