将读取文件中未删除的内容添加到文件

Add to file what's not deleted in read file

我正在尝试从一个文件中读取、添加到数组并删除它。我担心的是,如果某些记录无法删除,我想将它们保存到另一个文件中。只是不知道该怎么做:(

String deviceGUID;
List<String> listaGuida = new ArrayList<String>();
File file = new File("test.txt");

try {
  Scanner sc = new Scanner(file);
  while (sc.hasNextLine()) {
    deviceGUID = sc.nextLine();
    System.out.println(deviceGUID);
    listaGuida.add(deviceGUID);
  }
  sc.close();
} catch (FileNotFoundException e) {
  logger.log(Level.INFO, "Missing file!", e);
}

String[] temp = listaGuida.toArray(new String[0]);
for (String list : temp) {
  try {
    ServiceApi.remove(Long.parseLong(list));
    logger.log(Level.INFO, "All devices deleted!");
  } catch (ServiceApi ex) {
    logger.log(Level.SEVERE, "Unable to delete device: " + list, ex);
  } finally { 
    ???    
  }
}

猜猜代码会进入finally块吗?

很简单:

List<String> itemsThatCouldNotBeDeleted = new ArrayList<>();

在你的第二个 try 块前面的某个地方。

在 catch 块中,您调用 itemsThatCouldNotBeDeleted.add(whatever)

最后,在 finally 块中,检查该列表是否为空;如果不;您可以随心所欲地处理该内容。

换句话说:如果你想收集元素,那就把它们放在某种集合中;然后迭代该集合并做任何您想做的事情。

将列表写入文件也很简单;并已多次记录在这里;例如,参见 this