java - 如何在抛出 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);
}
}
}
解决方案
推荐阅读
- python - python函数中默认参数的值
- python - 如何在列表理解中执行作业?
- python - 从列表字典中删除记录
- python - 使用递归获取数字的总和
- javascript - 为什么标记 loadstart 事件不触发?有替代方案吗?
- c# - 如何确保单实例应用程序(在多个虚拟桌面上)?
- angular - ion-virtual-scroll 不是已知元素
- reactjs - 模态的 react-transition-group 的基本情况不起作用(codesandbox),为什么?
- r - 对半个数据集的列进行随机化
- python - 尽管尝试了各种解决方案,但 Jupyter Notebook 未上传 CSV 文件