Java InputStream到文件的示例

本文介绍在Java中如何使用InputStream读取二进制数据,并通过OutputStream将这些数据写入新文件,提供了一个简单的示例。

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

Files can be read using Reader or Stream in java. The Reader is good to use for text data but to work with binary data you should use Stream. FileInputStream is used to open the stream to read data from file. Here we will convert InputStream to file in Java, we will use OutputStream to write the new file.

可以使用Reader或Java中的Stream读取文件。 Reader适用于文本数据,但要使用二进制数据,应使用Stream。 FileInputStream用于打开流以从文件读取数据。 在这里,我们将InputStream转换为Java中的文件,我们将使用OutputStream编写新文件。

InputStream到文件 (InputStream to File)

InputStreamToFile.java

InputStreamToFile.java

package com.journaldev.files;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class InputStreamToFile {

    public static void main(String[] args) {
        try {
            InputStream is = new FileInputStream("/Users/pankaj/source.txt");
            
            OutputStream os = new FileOutputStream("/Users/pankaj/new_source.txt");
            
            byte[] buffer = new byte[1024];
            int bytesRead;
            //read from is to buffer
            while((bytesRead = is.read(buffer)) !=-1){
                os.write(buffer, 0, bytesRead);
            }
            is.close();
            //flush OutputStream to write any buffered data to file
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

That’s all for a simple example to convert InputStream to file in java.

这就是一个简单的示例,将InputStream转换为java中的文件。

翻译自: https://www.journaldev.com/918/java-inputstream-to-file-example

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值