Java文件流之字节流

本文介绍了使用Java进行文件的读取和写入操作的具体实现方式,包括使用InputStream和OutputStream进行文件复制、读取和写入的基本流程,并给出了具体的代码示例。

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

InputStream 与OutputStream是字节流中的输入流和输出流。

public class FileStream {

    public static void main(String[] args) {
        FileStream fs = new FileStream();
        // String content =
        // fs.readFileWithInputStream("/home/rding/file/File1.txt");
        // System.out.println(content);

        fs.writeFileWithOutputStream("/home/rding/file/File3.txt", "Hello File3");

        // fs.copyFile("/home/rding/file/File3.txt",
        // "/home/rding/file/File4.txt");

    }

    public void copyFile(String srcPath, String descPath) {
        InputStream inStream = null;
        OutputStream outStream = null;
        try {
            inStream = new FileInputStream(srcPath);
            outStream = new FileOutputStream(descPath);
            int size = inStream.available();
            byte[] byteArr = new byte[size];
            inStream.read(byteArr);
            outStream.write(byteArr);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void writeFileWithOutputStream(String filePath, String content) {
        OutputStream outStream = null;
        byte[] byteArr = content.getBytes();
        try {
        //注意,outStream第一次建立后,就不会更新了,必须关闭再重新建立 outStream
= new FileOutputStream(filePath); // outStream = new FileOutputStream(new File(filePath));        // 如果传入参数true,则接着原来文件后面继续写,而不是覆盖源文件。 // outStream = new FileOutputStream(filePath, true); // outStream = new FileOutputStream(new File(filePath), true); outStream.write(byteArr); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (outStream != null) { try { outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } public String readFileWithInputStream(String filePath) { InputStream inStream = null; String result = ""; try { inStream = new FileInputStream(filePath); // inStream = new FileInputStream(new File(filePath)); int size = inStream.available(); byte[] byteArr = new byte[size]; inStream.read(byteArr); result = new String(byteArr); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } }

 

转载于:https://www.cnblogs.com/lfdingye/p/7514065.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值