楼主: Lisrelchen
1543 0

Copying File Contents using Java [推广有奖]

  • 0关注
  • 62粉丝

VIP

已卖:4194份资源

院士

67%

还不是VIP/贵宾

-

TA的文库  其他...

Bayesian NewOccidental

Spatial Data Analysis

东西方数据挖掘

威望
0
论坛币
50288 个
通用积分
83.6306
学术水平
253 点
热心指数
300 点
信用等级
208 点
经验
41518 点
帖子
3256
精华
14
在线时间
766 小时
注册时间
2006-5-4
最后登录
2022-11-6

楼主
Lisrelchen 发表于 2015-6-5 10:53:43 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
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.

  1. Example 3-2. FileCopy.java
  2. package je3.io;
  3. import java.io.*;

  4. /**
  5. * This class is a standalone program to copy a file, and also defines a
  6. * static copy( ) method that other programs can use to copy files.
  7. **/
  8. public class FileCopy {
  9.     /** The main( ) method of the standalone program.  Calls copy( ). */
  10.     public static void main(String[  ] args) {
  11.         if (args.length != 2)    // Check arguments
  12.             System.err.println("Usage: java FileCopy <source> <destination>");
  13.         else {
  14.             // Call copy( ) to do the copy; display any error messages
  15.             try { copy(args[0], args[1]); }
  16.             catch (IOException e) { System.err.println(e.getMessage( )); }
  17.         }
  18.     }
  19.    
  20.     /**
  21.      * The static method that actually performs the file copy.
  22.      * Before copying the file, however, it performs a lot of tests to make
  23.      * sure everything is as it should be.
  24.      */
  25.     public static void copy(String from_name, String to_name)
  26.         throws IOException
  27.     {
  28.         File from_file = new File(from_name);  // Get File objects from Strings
  29.         File to_file = new File(to_name);
  30.         
  31.         // First make sure the source file exists, is a file, and is readable.
  32.         // These tests are also performed by the FileInputStream constructor,
  33.         // which throws a FileNotFoundException if they fail.
  34.         if (!from_file.exists( ))
  35.             abort("no such source file: " + from_name);
  36.         if (!from_file.isFile( ))
  37.             abort("can't copy directory: " + from_name);
  38.         if (!from_file.canRead( ))
  39.             abort("source file is unreadable: " + from_name);
  40.         
  41.         // If the destination is a directory, use the source file name
  42.         // as the destination file name
  43.         if (to_file.isDirectory( ))
  44.             to_file = new File(to_file, from_file.getName( ));
  45.         
  46.         // If the destination exists, make sure it is a writeable file
  47.         // and ask before overwriting it.  If the destination doesn't
  48.         // exist, make sure the directory exists and is writeable.
  49.         if (to_file.exists( )) {
  50.             if (!to_file.canWrite( ))
  51.                 abort("destination file is unwriteable: " + to_name);
  52.             // Ask whether to overwrite it
  53.             System.out.print("Overwrite existing file " + to_file.getName( ) +
  54.                              "? (Y/N): ");
  55.             System.out.flush( );
  56.             // Get the user's response.
  57.             BufferedReader in=
  58.                 new BufferedReader(new InputStreamReader(System.in));
  59.             String response = in.readLine( );
  60.             // Check the response.  If not a Yes, abort the copy.
  61.             if (!response.equals("Y") && !response.equals("y"))
  62.                 abort("existing file was not overwritten.");
  63.         }
  64.         else {  
  65.             // If file doesn't exist, check if directory exists and is
  66.             // writeable.  If getParent( ) returns null, then the directory is
  67.             // the current dir.  so look up the user.dir system property to
  68.             // find out what that is.
  69.             String parent = to_file.getParent( );  // The destination directory
  70.             if (parent ==== null)     // If none, use the current directory
  71.                 parent = System.getProperty("user.dir");
  72.             File dir = new File(parent);          // Convert it to a file.
  73.             if (!dir.exists( ))
  74.                 abort("destination directory doesn't exist: "+parent);
  75.             if (dir.isFile( ))
  76.                 abort("destination is not a directory: " + parent);
  77.             if (!dir.canWrite( ))
  78.                 abort("destination directory is unwriteable: " + parent);
  79.         }
  80.         
  81.         // If we've gotten this far, then everything is okay.
  82.         // So we copy the file, a buffer of bytes at a time.
  83.         FileInputStream from = null;  // Stream to read from source
  84.         FileOutputStream to = null;   // Stream to write to destination
  85.         try {
  86.             from = new FileInputStream(from_file);  // Create input stream
  87.             to = new FileOutputStream(to_file);     // Create output stream
  88.             byte[  ] buffer = new byte[4096];         // To hold file contents
  89.             int bytes_read;                         // How many bytes in buffer

  90.             // Read a chunk of bytes into the buffer, then write them out,
  91.             // looping until we reach the end of the file (when read( ) returns
  92.             // -1).  Note the combination of assignment and comparison in this
  93.             // while loop.  This is a common I/O programming idiom.
  94.             while((bytes_read = from.read(buffer)) != -1) // Read until EOF
  95.                 to.write(buffer, 0, bytes_read);            // write
  96.         }
  97.         // Always close the streams, even if exceptions were thrown
  98.         finally {
  99.             if (from != null) try { from.close( ); } catch (IOException e) { ; }
  100.             if (to != null) try { to.close( ); } catch (IOException e) { ; }
  101.         }
  102.     }

  103.     /** A convenience method to throw an exception */
  104.     private static void abort(String msg) throws IOException {
  105.         throw new IOException("FileCopy: " + msg);
  106.     }
  107. }
复制代码


二维码

扫码加我 拉你入群

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

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

关键词:contents Content Using COPY Java specified contents another example source

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
jg-xs1
拉您进交流群
GMT+8, 2026-1-4 05:05