Java代码来实现以下功能(测试字节输入流和字节输出流)

package io.uiti2;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
public class Hello1 {

@Test//测试字节输入流 -- 一次读一个字节
public void fun3() throws IOException {
    //相对路径
    File f1 = new File("src/b.txt");
    System.out.println(f1.length());//119

    //1.构建一条通向文件f1的管道--流对象
    FileInputStream fis = new FileInputStream(f1);

    //2.调用方法 -- 根据文件的字节长度,去构建一个相同长度的数组
    byte[] bs = new byte[fis.available()];

    fis.read(bs);
    String str =new String(bs);
    System.out.println(str);

    //关闭资源
    fis.close();
}

@Test//测试字节输入流 -- 一次读一个字节
public void fun2() throws IOException {
    //相对路径
    File f1= new File("src/a.txt");
    System.out.println(f1.length());//10

    //1.构建一条通向文件f1的管道--流对象
    FileInputStream fis = new FileInputStream(f1);

    //2.调用方法 -- 根据文件的字节长度,去构建一个相同长度的数组
    byte[] bs = new byte[fis.available()];

    //读取到文件中的字节数据,存入数组中,返回督导的实际字节个数
    int r1 = fis.read(bs);
    int r2 = fis.read(bs);
    System.out.println(Arrays.toString(bs));
    System.out.println(r1);//10
    System.out.println(r2);//-1

    //关闭资源
    fis.close();
}

@Test//测试字节输入流 -- 一次读一个字节
public void fun1() throws IOException {
    //绝对路径
    File f1 = new File("D:\\培训\\ideaworkspace\\day20-java20\\src\\a.txt");
    System.out.println(f1.exists());
    //相对路径
    File f2 = new File("src/a.txt");
    System.out.println(f2.exists());

    //1.构建一条通向文件f2的管道
    FileInputStream fis = new FileInputStream(f2);
    //2.调用方法
    int l = fis.available();
    for (int i = 0; i < 1; i++) {
        System.out.println(fis.read());
    }
    //关闭资源
    fis.close();

}

}

package io.uiti2;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;

public class Hello2 {

//字节输出流
@Test
public void fun1() throws IOException {
    FileOutputStream os = new FileOutputStream("src/c.txt");
    //写一个字节
    //os.write(79);

    //写一个字节数组
    /*os.write(("将下面的语句写入一个文本文件中:\n" +
        "I know,I'm not good enough, but I'm the only one in the world." +
            " Please cherish it.").getBytes());*/
    os.write(("I know,I'm not good enough, but I'm the only one in the world." +
            " Please cherish it.").getBytes(),2,4);

}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值