全部版块 我的主页
论坛 数据科学与人工智能 IT基础 JAVA语言开发
1488 0
2015-06-05
Copying File Contents using Java

Example 3-2 shows a program that copies the contents of a specified file to another file. This example uses the File class, much as Example 3-1 did, to check that the source file exists, that the destination is writable, and so on. But it also introduces the use of streams to work with the contents of files. It uses a FileInputStream to read the bytes of the source file and a FileOutputStream to copy those bytes to the destination file.

The copy( ) method implements the functionality of the program. This method is heavily commented, so that you can follow the steps it takes. First, it performs a surprisingly large number of checks to verify that the copy request is a legitimate one. If all those tests succeed, it then creates a FileInputStream to read bytes from the source and a FileOutputStream to write those bytes to the destination. Notice the use of a byte array buffer to store bytes during the copy. Pay particular attention to the short while loop that actually performs the copy. The combination of assignment and testing in the condition of the while loop is a useful idiom that occurs frequently in I/O programming. Also notice the finally statement that ensures the streams are properly closed before the program exits.

In addition to using streams to read from and write to files, this program also uses streams to read from and write to the console. Before overwriting an existing file, this example asks for user confirmation. It demonstrates how to read lines of text with a BufferedReader that reads individual characters from an InputStreamReader, which in turn reads bytes from System.in (an InputStream), which reads keystrokes from the user’s keyboard. Additionally, the program displays textual output with System.out and System.err, which are both instances ofPrintStream.

The static FileCopy.copy( ) method can be called directly by any program. The FileCopy class also provides a main( ) method, however, so that it can be used as a standalone program.

复制代码


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群