复习io流(一)

之前也学习过io流,但是时间太长了,所以来复习一下。
1.1文件流
文件是在程序之中是以流的形式来操作的。
在这里插入图片描述

输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从内存到文件的路径。
.方式一 new File(String pathname)

   @Test
    public void create01(){
        String filepath="D:\\untitled3\\src\\io\\wenjian.txt";
        File file = new File(filepath);
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

方式二 new File(File parent,String child) //父目录文件 +子路径构建

 @Test
    public void create02()  {
        File ParentFile = new File("D:\\untitled3\\src\\io");
        String fileName="wenjian1.txt";
        File file = new File(ParentFile, fileName);
        try {
            file.createNewFile();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

方式三

    @Test
  public void create03() throws IOException {
      String parentPath="D:\\untitled3\\src\\io";
      String fileName="wenjian2.txt";

      File file = new File(parentPath, fileName);

       file.createNewFile();
      System.out.println("文件创建成功");
  }

基本多是api的调用,我就快速的看看了。。。
文件的读取
FileInputStream 字节流读取,效率比较低

@Test
  public void readFile01() throws IOException {
      String filePath="D:\\untitled3\\src\\io\\wenjian.txt";
//        创建fileInputStream对象,用来读取文件
      FileInputStream fileInputStream = new FileInputStream(filePath);
      int readData=0;
//
      while( (readData=fileInputStream.read())!=-1){
          System.out.print((char)readData);
      }
      fileInputStream.close();
  }

用字节数组的形式转化为字符串(String)

   @Test
   public void readFile2() throws IOException {
        String FilePath="D:\\untitled3\\src\\io\\wenjian.txt";
       int readLenth=0;
        byte[] bytes = new byte[8];
        FileInputStream fileInputStream = new FileInputStream(FilePath);
        while ((readLenth=fileInputStream.read(bytes))!=-1){
            System.out.println(new String(bytes,0, readLenth));
        }
    }
   // 可以看看String这个构造器的源码
 /*   public String(byte bytes[], int offset, int length) {
        checkBounds(bytes, offset, length);
       // bytes – 要解码为字符的字节
		//offset – 要解码的第一个字节的索引
		//length - 要解码的字节数
        this.value = StringCoding.decode(bytes, offset, length);
    }
    
    */

把内容写入文件

   @Test
    public void writeFile() throws IOException {
//        创建FileoutputStream
        String filepath="D:\\untitled3\\src\\io\\wenjian.txt";
        //        new FileOutputStream(filepath,true); 追加内容
        FileOutputStream fileOutputStream = new FileOutputStream(filepath);
        String str="hello world aaaaa";
        fileOutputStream.write(str.getBytes()); //字符串转化为字节数组
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值