FileInputStream和FileOutputStream读写文件

package com.yang;

import org.junit.Test;

import java.io.*;

/**
 * FileInputstream和FileOutputStream的使用
 */
public class FileReaderWriterTest {

    /**
     * 读入流
     * @throws IOException
     */
    @Test
    public void testFileReader() throws IOException {
     //造文件
     File  file=new File("file.txt");
     //造流
     FileInputStream fis=new FileInputStream(file);
     //读取数据
//      字节数组
     byte[]buffer=new byte[20];
     int len;
     while ((len=fis.read(buffer))!=-1){
         String str=new String(buffer,0,len);
         System.out.println(str);
     }
     fis.close();
    }



}

读取图片
文件用字节流,非文件用字符流

package com.yang;

import org.junit.Test;

import java.io.*;

/**
 * FileInputstream和FileOutputStream的使用
 */
public class FileReaderWriterTest {

    /**
     * 读入流
     * @throws IOException
     */
    @Test
    public void testFileReader() throws IOException {
     //造文件
     File  file=new File("1.png");
        File  file1=new File("2.png");
     //造流
     FileInputStream fis=new FileInputStream(file);
     FileOutputStream out=new FileOutputStream(file1);
     //读取数据
//      字节数组
     byte[]buffer=new byte[5];
     int len;
     while ((len=fis.read(buffer))!=-1){
        out.write(buffer,0,len);
     }
     fis.close();
     out.close();
    }



}

缓冲流实现非文本文件的复制

package com.yang;

import org.junit.Test;

import java.io.*;

/**
 * FileInputstream和FileOutputStream的使用
 */
public class FileReaderWriterTest {

    /**
     * 读入流
     * @throws IOException
     */
    @Test
    public void testFileReader() throws IOException {
     //造文件
     File  file=new File("1.png");
     File  destFile=new File("2.png");
//     造节点流 文件流
     FileInputStream fis=new FileInputStream(file);
     FileOutputStream fos=new FileOutputStream(destFile);
//     造缓存流
     BufferedInputStream bis=new BufferedInputStream(fis);
     BufferedOutputStream bos=new BufferedOutputStream(fos);

//     字节数组
     byte[]buffer=new byte[10];
     int len;
     while ((len=bis.read(buffer))!=-1){
         bos.write(buffer,0,len);
     }

     bos.close();
     bis.close();
    
    }



}

缓冲流实现文件的复制

  /**
     * 读入流
     * @throws IOException
     */
    @Test
    public void testFileReader() throws IOException {
        BufferedReader  br=new BufferedReader(new FileReader(new File("file.txt")));
        BufferedWriter  bw=new BufferedWriter(new FileWriter(new File("file1.txt")));
        char[]cbf=new char[1024];
        int len;
        while ((len=br.read(cbf))!=-1){
            bw.write(cbf,0,len);
            bw.flush();
        }
        bw.close();
        br.close();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值