首页 > 解决方案 > 如何在抛出 FILENOTFOUNDEXCEPTION 后恢复我离开的代码

问题描述

我正在将文件写入目录。目录可能无法访问。

我想做的是..

我的问题是,当抛出未找到文件的异常时,程序会一起关闭。这是我的代码:

public class BusStopsProcessor implements Runnable
{
  private BlockingQueue<Bus<buses>> busQueue;

  private Bus<buses> BusObject; 

  public BusStopsProcessor(BlockingQueue<Bus<buses>> busQueue) 
  {
    this.busQueue = busQueue;
  }

@Override
public void run() 
{
    try 
    {
        String path = "C:\\Users\\Me\\Documents\\";         
        File file = new File(path + "busStopsFile.txt");

        FileWriter fw = new FileWriter(file, true);
        CSVWriter writer = new CSVWriter(fw, '|', CSVWriter.NO_QUOTE_CHARACTER);

        while(true) 
        {
            BusObject = busQueue.take();

            //each bus object should have a bus date if it does not then it is a 
            //poison bus object. 
            if(BusObject.getBusDate() != null) 
            {
                createBusFile(BusObject, writer);

            else 
            {
                try 
                {
                    //Finished processing bus stops so close writer.
                    writer.close();
                    fw.close();                     

                    break;
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
        }

    } 
    catch (InterruptedException e) 
    {
        Thread.currentThread().interrupt();
        e.printStackTrace();
    }
    catch (FileNotFoundException e) 
    {
                    //If a  FILENOTFOUND exception is thrown here I want
                    //my code to be able to pick up where I left off

        e.printStackTrace();
        logger.warn(e.getMessage());
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
}

这是我想继续检查目录是否存在的方法。如果正在写入文件并且目录突然关闭。我不想在文件中重复相同的信息,我希望它从停止的地方继续写入,但我不知道该怎么做。谢谢你。

    private void createBusFile(Bus<buses> aBusObject, CSVWriter writer) throws InterruptedException 
{
    //Get bus information here
    for(Bus<buses> busStop : aBusObject.getBusStops()) 
    {
        busNumber = busStop.getBusNumber();
        busArrivalTime = busStop.getBusArrivalTime();
        busStop = busStop.getBusStop();

        String[] busFields = {busNumber, busDate, busStop};

        //If a file not found exception is thrown here I want it to keep checking if the directory exists. And pick up from where I left off
        writer.writeNext(busFields);

    }

}

}

标签: java

解决方案


推荐阅读