java - 处理目录和文件时处理 IO 异常的最佳实践?

标签 java file inputstream outputstream ioexception

示例代码如下。它将目标文件和目录从一个位置复制到另一个位置。通过网络复制文件时处理 IO 异常的最佳实践是什么?

我使用了 printStackTrace() 但感觉这只是一个更好的解决方案的占位符。记录是答案吗?除了记录之外是否应该采取另一个步骤来实际“处理”错误?

感谢您的反馈。

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

/**
   This is a test program to copy a directory(s) & file(s) from one location to another.
*/

public class CopyTest{

   public static void main(String[] args) {

      //Declarations 
      String sourcePath = "I:\\MB\\PO"; 
      String destPath = "C:\\testPO\\";  
      System.out.println("Source path:  " + sourcePath);  
      System.out.println("Destination path:  " + destPath);  
      File source = new File(sourcePath);  
      File dest = new File(destPath);  

      //Process
      //Call to method copyUsingStream
      long start = System.nanoTime(); //start recording how much time the copy takes.
      copyUsingStream(source, dest);  //method to copy the directory/files.
      System.out.println("Time taken to copy the file: "+(System.nanoTime() -start) + " nanoseconds");

   } //end main method

   /**
      The copyUsingStream method is a recursive method to copy folders and files from one location to another.
   */

   private static void copyUsingStream(File source, File dest) {   

      if (!source.isDirectory()){ 
         // If source is a file -> copy it to the new folder
         InputStream inStream = null;
         OutputStream outStream = null;
         try {
            inStream = new FileInputStream(source);
            outStream = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;

            while ((length = inStream.read(buffer)) > 0) {
               outStream.write(buffer, 0, length);
            }
         } catch(IOException ioe) {
            ioe.printStackTrace();
         } finally {
            try{
               inStream.close();
               outStream.close();
               System.out.println("File copied from " + source + " to " + dest + "successfully");
            } catch(IOException ioe2) {
               ioe2.printStackTrace();
            }
         } 
      } else {

         //If a directory -> create the directory inside the new destination
         //List all contents

         if (!dest.exists()) {
            dest.mkdir();
            System.out.println("Directory copied from " + source + " to " + dest + "successfully");
         }

         String folder_contents[] = source.list();

         for (String file : folder_contents) {

            File srcFile = new File(source, file);
            File destFile = new File(dest, file);

            copyUsingStream(srcFile, destFile);

         }

      }

   } //end method copyUsingStream

} //end class CopyTest

没有捕获的方法:

   private static void copyUsingStream(File source, File dest) throws IOException {   

      if (!source.isDirectory()){ 
         // If source is a file -> copy it to the new folder
         InputStream inStream = null;
         OutputStream outStream = null;
         try {
            inStream = new FileInputStream(source);
            outStream = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;

            while ((length = inStream.read(buffer)) > 0) {
               outStream.write(buffer, 0, length);
            }
         } finally {
               inStream.close();
               outStream.close();
               System.out.println("File copied from " + source + " to " + dest + "successfully");
         } 
      } else {

         //If a directory -> create the directory inside the new destination
         //List all contents

         if (!dest.exists()) {
            dest.mkdir();
            System.out.println("Directory copied from " + source + " to " + dest + "successfully");
         }

         String folder_contents[] = source.list();

         for (String file : folder_contents) {

            File srcFile = new File(source, file);
            File destFile = new File(dest, file);

            copyUsingStream(srcFile, destFile);

         }

      }

   } //end method copyUsingStream

最佳答案

这很大程度上取决于您的应用程序。

无论如何都会继续运行的应用程序(例如网络服务器、守护进程和批处理处理器)通常会将此类错误与时间戳、线程 ID 和可能的其他有用信息一起记录在文件中。

我对两个日志文件的组合有非常好的经验。

  1. myapp.log 仅接收重要消息,通常是警告和错误。该文件适用于普通用户和系统运算符(operator)。
  2. debug.log 适用于开发人员。它提供错误发生前的调试消息,但只要一切正常,就不会显示任何消息。为了实现这一点,需要一个内存缓冲区。

如果您对该缓冲区感兴趣,可以查看 http://stefanfrings.de/bfUtilities/index.html 。该网站是德语的,但库及其文档是英语的。

在桌面 GUI 应用程序上,当错误中止请求的操作时,最好在弹出窗口中显示简短的错误消息,并在可扩展框中隐藏详细信息(堆栈跟踪)。不要忘记清楚地告诉用户什么操作失败了。异常本身对于开发人员来说可能足够清楚,但普通用户期望技术性较低的文本。例如:“从服务 Weather.com 加载天气信息失败:连接失败”,后面是堆栈跟踪。

对于立即停止的控制台应用程序,我更喜欢直接在屏幕上查看由 printStackTrace() 编写的堆栈跟踪。

关于java - 处理目录和文件时处理 IO 异常的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60120526/

相关文章:

node.js - 在不读取整个文件的情况下读取 Node.js 中的第 n 行

c - 将结果从一个文件传递到另一个文件

java - ObjectInputStream 异常

java - 如何访问位于项目文件夹外部和项目类路径外部的 .properties 文件?

Java Spring : How to Get JSON/XML View from Controller on Forward or Redirect?

Java:java.util.NoSuchElementException:找不到行

java - Android 和 SSL 证书加载

arrays - 无法将文件放入 redux 数组

java - BufferedInputStream 读取与 IOUtils toByteArray 比较

java - 缺少通用类类型的导入建议