java-IO流笔记

本文介绍了如何使用字节流进行文件的读取与写入操作,包括基本的字节流读写方法及利用缓冲流提高读写效率的技术。文中通过实例展示了FileInputStream和FileOutputStream的使用,并进一步说明了如何通过BufferedInputStream和BufferedOutputStream实现高效的文件复制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用字节流读写数据

使用字节流读文件

File file = new File("test.txt");
if (file.exists()){
   
try {
        file.createNewFile();
    }
catch (IOException e) {
        e.printStackTrace();
    }
}

try {
    FileInputStream fis =
new FileInputStream("test.txt");//输入流
   
byte input[] = new byte[20];//创建字节数组存放读取的字节
   
fis.read(input);//读取字节
   
String inputString = new String(input,"gbk");//将读取的字节赋予字符串,并编码
   
System.out.println(inputString);//输出字符串
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
catch (IOException e) {
    e.printStackTrace();
}

使用字节流写文件

FileOutputStream fos = new FileOutputStream(文件名);

String outString = “1233456567567”;

Byte output[] = outString.getBytes(“utf-8”);

Fos.write(output);

Fos.close();

带缓冲的字节流读写文件

try {

    FileInputStream fis = new FileInputStream("test.txt");

    BufferedInputStream bis = new BufferedInputStream(fis);

    FileOutputStream fos = new FileOutputStream("new test.txt");

    BufferedOutputStream bos = new BufferedOutputStream(fos);

    byte[] input = new byte[100];

    while (bis.read(input) != -1){

        bos.write(input);

    }

    bos.close();

    fos.close();

} catch (FileNotFoundException e) {

    e.printStackTrace();

} catch (UnsupportedEncodingException e) {

    e.printStackTrace();

} catch (IOException e) {

    e.printStackTrace();

}

有缓冲流可以更快速的读写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值