如何读取和写入字节流

Reading and writing binary streams is one of the most common I/O tasks a Java application can perform. It can be performed by looking at each individual byte in a stream or by using a more structured buffered approach.

读写二进制流是Java应用程序可以执行的最常见的I / O任务之一。 可以通过查看流中的每个单独字节或通过使用结构化的缓冲方法来执行。

Note: This article looks at reading binary data from a

注:本文着眼于读取二进制数据


example.jpg file. If you try this code then simply replace the name of the 
example.jpg with the path and name of a jpeg

逐字节 ( Byte by Byte )

The


java.ioclass was the first Java api to provide Input/Output functionality. It has two methods that can be used to input and output byte streams (blocks of 8 bits) from and to a file. These 
classes are the
FileInputStream and 
FileOutputStream. These methods provide a basic method of I/O by allowing a file to be input or output one byte at a time. In practice it's better to use a buffered method for binary streams but it's good to look at the most basic building block of the

Notice how we place the I/O handling inside a

注意我们如何将I / O处理放置在


try, catch, finallyblock—this is to make sure we handle IO exceptions and to properly close the streams. The catch block will show any I/O exceptions that occur and print a message for the user. In the finally block it's important to close the streams explicitly by calling the close method otherwise they will remain open and a waste of resources. There is a check to see if the 
FileInputStreamand 
FileOutputStreamare null before attempting to close. This is because an I/O error could occur before the streams are initialized. For example, if the file name is incorrect the stream will not be


tryblock we can add code t


readmethod reads in one byte from the 
FileInputStreamand the write method writes one byte to the 
FileOutputStream. When the 
end of the file is reached and there are no more bytes to input the v 文件末尾且没有更多字节可输入v

Now that Java 7 has been released you can see the benefit of one of its new features—the try with resources block. This means that if we identify the streams to the try block at the beginning it will handle closing the stream for us. This eliminates the need for the finally block in the previous example:

现在,Java 7已发布,您可以看到它的一项新功能的好处-尝试资源块。 这意味着,如果我们在开始时就识别到try块的流,它将为我们处理关闭流。 这消除了上一个示例中对finally块的需要:

The full Java code listings for the two versions of the byte reading program can be found in Binary Stream Example Code.

字节流程序的两个版本的完整Java代码列表可在Binary Stream Example Code中找到。

翻译自: https://www.thoughtco.com/how-to-read-and-write-byte-streams-2033914

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值