4

对于我的父母,我正在编写一个简单的程序来将文件从他们的数码相机复制到他们的“我的文档”文件夹中。他们总是需要我的帮助(他们的技术不是那么先进)才能把他们的照片从相机上取下来,所以我决定帮助他们。我把它叫做复印机。由于我在 Java 中找不到合适的 USB-Listener,我自己写了一个:

private void sync()
{
    // All devices in an ArrayList
    File[] roots = File.listRoots();
    ArrayList<File> newList = new ArrayList<File>();
    for(File f : roots)
    {
        newList.add(f);
    }

    // Delete unavailable devices
    ArrayList<File> removeThese = new ArrayList<File>();
    for(File f : devices)
    {
        if(!newList.contains(f))
        {
            removeThese.add(f);
        }
    }
    devices.removeAll(removeThese);

    // Add unknown devices
    for(File f : newList)
    {
        if(!devices.contains(f) && f.canRead() && f.canWrite())
        {
            alarm(f); // Called when new device inserted
            devices.add(f);
        }
    }
}

这个方法在一个单独的线程中每 1000 毫秒调用一次,我想这可以。承认,这是一种肮脏的方法,但它有效。我经常测试这个功能,我总是得到我想要的结果。当我继续构建我的程序时,我发现当我将程序隐藏到 SystemTray 时,线程将停止检测新设备。当我再次打开它时,检测线程仍然不起作用。谁能告诉我这是什么原因以及如何解决?

4

1 回答 1

2

保存用户插入的数据后,我停止检测新设备。这对我来说很愚蠢,所以我感谢你让我意识到这一点。

public boolean saveSettings() 
{
    File f = new File(fsv.getHomeDirectory() + File.separator + "settings.cms");
    ObjectOutputStream objOut;
    try 
    {
        // Here was my problem. 
        detector.stopDetection();

        if(gui.saveSettings())
        {
            // Settings-file wegschrijven
            objOut = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
            objOut.writeObject(settings);
            objOut.flush();
            objOut.close();
            return true;
        }
        else
        {
            return false;
        }
    } 
    catch (IOException e) 
    {
        handleExceptions(e);
        return false;
    }
}
于 2012-07-03T18:44:32.603 回答