如何在发生异常时重新启动文件上传

时间:2015-08-05 06:10:53

标签: java multithreading exception-handling ftp-client

我正在研究一个我遇到问题的java应用程序。当我将文件发送到服务器并抛出异常时,不会发送该文件。我该如何重试发送文件?

       public void uploadtxtFile(String localFileFullName, String fileName, String hostDir)
                throws Exception {
            File file = new File(localFileFullName);
            if (!(file.isDirectory())) {
                if (file.exists()) {
                    FileInputStream input = null;
                   try {
                        input = new FileInputStream(new File(localFileFullName));
                        if (input != null) {
                            hostDir = hostDir.replaceAll("//", "/");
                           logger.info("uploading host dir : " + hostDir);
                     //new 

//                       TestThread testThread=new TestThread(hostDir,input);
//                      Thread t=new Thread(testThread);
//                  
//                      try{
//                          t.start();
//                          
//                      }catch(Exception ex){
//                          logger.error("UPLOADE start thread create exception new:" + ex);
//                      }
//                      // new end

                        DBConnection.getFTPConnection().enterLocalPassiveMode();
                        // the below line exeption is come
                      boolean bool = DBConnection.getFTPConnection().storeFile(hostDir, input);
                       //input.close();//new comment
                           if (bool) {
                               logger.info("Success uploading file on host dir :"+hostDir);
                          } else {
                                logger.error("file  not uploaded.");
                        }
                      } else {
                             logger.error("uploading file input null.");
                 }
                 }catch(CopyStreamException cs)
                    {   logger.error("Copy StreamExeption is come "+cs);
                    } catch(Exception ex)
                    {
                         logger.error("Error in connection ="+ex);//this is catch where I handle the exeption

                    }finally {
    //                  boolean disconnect= DBConnection.disConnect();
                        input.close();
                   }

                } else {
                     logger.info("uploading file is not exists.");
                }
            }
        }

这是代码,我想重新启动文件上传,但我不知道。我尝试使用线程,但异常再次抛出。我也尝试使用while循环,但它无限循环并且还显示异常以及另一个异常。 下面是我使用的线程代码:

public void run() {

               System.out.println("Enter Thread TestThread");

               DBConnection.getFTPConnection().enterLocalPassiveMode();
                 //  System.out.println("Error in DBConnection ");
                  //here server timeout error is get


                  boolean bool1=false;

                   boolean bool=true;
                    try {
                    bool = DBConnection.getFTPConnection().storeFile(hostDir1, input1);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    e.printStackTrace();


                    }finally {
                        //disconnect();

                    try {
                    input1.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                        e.printStackTrace();
                        }
                   }

                   if (bool) {
                       System.out.println("File is Uploded");
                    } else {

                    while(bool!=true){
                    try {
                         DBConnection.getFTPConnection().enterLocalPassiveMode();
                            bool1=DBConnection.getFTPConnection().storeFile(hostDir1, input1);

                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }finally {
                            //disconnect();

                            try {
                            input1.close();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                            e.printStackTrace();
                            }
                    }
                     System.out.println("file  not uploaded."+bool1);
                         bool=bool1;
                   }
            }
              }
    }
              }

任何人都可以找到如何将文件上传到服务器的解决方案吗?

例外如下所示:

  1. 软件导致连接中止:recv failed
  2. 软件导致连接中止:套接字写入错误
  3. org.apache.commons.net.io.CopyStreamException:复制时捕获到IOException。

3 个答案:

答案 0 :(得分:0)

在您调用需要重试的方法的类中添加如下的静态类:

static class RetryOnExceptionStrategy {
public static final int DEFAULT_RETRIES = 3;
public static final long DEFAULT_WAIT_TIME_IN_MILLI = 2000;

private int numberOfRetries;
private int numberOfTriesLeft;
private long timeToWait;

public RetryOnExceptionStrategy() {
    this(DEFAULT_RETRIES, DEFAULT_WAIT_TIME_IN_MILLI);
}

public RetryOnExceptionStrategy(int numberOfRetries,
        long timeToWait) {
    this.numberOfRetries = numberOfRetries;
    numberOfTriesLeft = numberOfRetries;
    this.timeToWait = timeToWait;
}

/**
 * @return true if there are tries left
 */
public boolean shouldRetry() {
    return numberOfTriesLeft > 0;
}

public void errorOccured() throws Exception {
    numberOfTriesLeft--;
    if (!shouldRetry()) {
        throw new Exception("Retry Failed: Total " + numberOfRetries
                + " attempts made at interval " + getTimeToWait()
                + "ms");
    }
    waitUntilNextTry();
}

public long getTimeToWait() {
    return timeToWait;
}

private void waitUntilNextTry() {
    try {
        Thread.sleep(getTimeToWait());
    } catch (InterruptedException ignored) {
    }
}
}   

现在在while循环中将您的方法调用包装如下:

RetryOnExceptionStrategy errorStrategy=new RetryOnExceptionStrategy();
while(errorStrategy.shouldRetry()){
try{
 //Method Call
}
catch(Exception excep){
 errorStrategy.errorOccured();
}
}

基本上你只是在while循环中包装方法调用 保持returnig为真,直到你的重试次数达到零,说你从3开始。

每次发生异常时,都会捕获异常并调用方法 这将减少你的retryCount和方法调用再次执行一些延迟。

答案 1 :(得分:0)

使用此类应用程序的一般方法是:

  1. 创建一个类,例如UploadWorker,它将Callable扩展为包装器。使包装器返回失败时所需的任何错误和详细信息。
  2. 为此包装器创建一个ExecutorService(基本上是一个线程池),以便在线程中运行。
  3. 提交您的UploadWorker个实例,然后获得Future。在未来调用get()以阻止方式或等待一段时间获得结果。
  4. 如果get()返回错误消息,请再次将您的工作人员提交给线程池。

答案 2 :(得分:0)

取走uploadtxtFile中的try / catch内容,让它抛出,然后使用类似Failsafe的内容来执行重试:

RetryPolicy retryPolicy = new RetryPolicy()
  .retryOn(CopyStreamException.class)
  .withDelay(1, TimeUnit.SECONDS)
  .withMaxRetries(5);

Failsafe.with(retryPolicy).run(() -> uploadtxtFile(.....));

它不会变得简单得多。