Java基础知识字节流练习

it2022-05-05  169

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)