文件字节流

package IO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test1 {
public static void main(String[] args) {
//想控制输入文件信息
// Test1.testFileInputStream();
//将代码信息输出到文件
// Test1.testFileoutputStream();
// 将一个位置的文件cp到另一个位置
Test1.copyFile(“F:\IO_test\test\img.png”,“F:\IO_test\test\tt\img.png”);

}

/**
 * 文件字节输入流
 */
public static void testFileInputStream(){
    try {
        FileInputStream in = new FileInputStream("F:\\IO_test\\test\\tt1.txt");
        byte[] b =new byte[15]; //设置一个byte数组接受读取文件的内容

// in.read(b); // read 方法有一个返回值 返回值是读取的数据的长度,如果读取到最后一个数据,还会向后读一个,
//也就意味着当im read的返回值是- 1的时候整个文件就读取完毕了
int len=0;
while ((len = in.read(b)) != -1 ){
System.out.println(new String(b,0,len));
//new String(b,0,len 参数1是缓冲数据的数组,参数2是从数组的那个位置开始转化字符串,
// 参数3是总共转化几个字节
}
in.close(); //注意流在使用完毕后一定要关闭
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
 * 文件字节输出流FileOutputStream
 */
public static void testFileoutputStream(){
    try {
        FileOutputStream out = new FileOutputStream("F:\\IO_test\\test\\tt1.txt"); //向指定的文件输出数据
        String str = "tom is root";
        out.write(str.getBytes()); // 把数据写到内存中
        out.flush();//把内存中的数据刷写到硬盘
        out.close();//关闭流
    } catch (Exception e) {
        e.printStackTrace();
    }

}

/**
 * 复制文件到指定位置
 * @param inPath
 * @param outPath
 */
public static void copyFile (String inPath,String outPath){
    try {
        FileInputStream in = new FileInputStream(inPath);
        FileOutputStream out = new FileOutputStream(outPath);
        byte[] b =new byte[15];
        int len=0;
        while ((len = in.read(b)) != -1 ) {
            out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值