文件输入/输出流

FileInputStream与FileOutputStream类
用来操作文件,但存在不足,就是这两个类只提供了对字节或字节数组的读取方法。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Fileinputstream {
    public static void main(String [] args)
    {
        File file= new File("work1.txt");//创建文件
        if(file.exists())//判断文件是否存在
        {
            file.delete();//如果存在删除
            System.out.println("file is delete");
        }
        else
        {
            try{
                FileOutputStream out = new FileOutputStream(file);//写
                byte buy[] = "I am a boy.".getBytes();
                out.write(buy);
                out.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            }

            try
            {
                FileInputStream in = new FileInputStream(file);//读
                byte but[] = new byte[1024];
                int len = in.read(but);

                System.out.println(new String(but, 0 , len));
                in.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是实现文件拷贝的程序: ```java import java.io.*; public class FileCopy { public static void main(String[] args) { // 从控制台获取源文件名和目标文件名 Scanner scanner = new Scanner(System.in); System.out.print("请输入文件名:"); String srcFileName = scanner.nextLine(); System.out.print("请输入目标文件名:"); String destFileName = scanner.nextLine(); // 创建文件输入/输出和缓冲 FileInputStream fis = null; BufferedInputStream bis = null; FileOutputStream fos = null; BufferedOutputStream bos = null; try { fis = new FileInputStream(srcFileName); bis = new BufferedInputStream(fis); fos = new FileOutputStream(destFileName); bos = new BufferedOutputStream(fos); // 读取源文件并写入目标文件 byte[] buffer = new byte[1024]; int len; while ((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len); } // 输出拷贝成功消息 System.out.println("文件拷贝成功!"); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭 try { if (bos != null) { bos.close(); } if (fos != null) { fos.close(); } if (bis != null) { bis.close(); } if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } } } ``` 程序使用了 `Scanner` 类从控制台获取源文件名和目标文件名,然后创建了文件输入/输出和缓冲,以便实现高效的文件读取和写入。在读取源文件时,程序每次读取 1024 个字节,并将这些字节写入目标文件。最后,程序关闭所有输出拷贝成功消息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值