0

我有一个程序,我想从检测到的 USB 驱动器(可移动存储,如 USB)上运行,这是通过创建两个类来完成的:external.java 和 DetectDrive.java,如下所示:

外部.java

 public class external
 {
    public static void main(String args[]) throws InterruptedException  
    {

    DetectDrive d = new DetectDrive();
    String DetectDrive = d.USBDetect();
    BufferedWriter fileOut;
    String filePath = DetectDrive;
    System.out.println(filePath);

    try 
        {
        fileOut = new BufferedWriter(new FileWriter("F:\\external.bat"));
        fileOut.write("cd "+ filePath +"\n");
        fileOut.write("external.exe"+"\n");

        fileOut.close(); //close the output stream after all output is done
        Runtime rt = Runtime.getRuntime();
        Process p = rt.exec("cmd /c start" +DetectDrive+ "\\external.bat");
        p.waitFor();
        } catch (IOException e){
            e.printStackTrace();
            }       
    }
}

DetectDrive.java

import java.io.*;
import java.util.*;
import javax.swing.filechooser.FileSystemView;

public class DetectDrive
{
    public String USBDetect()
    {
        String driveLetter = "";
        FileSystemView fsv = FileSystemView.getFileSystemView();

        File[] f = File.listRoots();
        for (int i = 0; i < f.length; i++)
        {
            String drive = f[i].getPath();
            String displayName = fsv.getSystemDisplayName(f[i]);
            String type = fsv.getSystemTypeDescription(f[i]);
            boolean isDrive = fsv.isDrive(f[i]);
            boolean isFloppy = fsv.isFloppyDrive(f[i]);
            boolean canRead = f[i].canRead();
            boolean canWrite = f[i].canWrite();

            if (canRead && canWrite && !isFloppy && isDrive && (type.toLowerCase().contains("removable") || type.toLowerCase().contains("rimovibile")))
            {
                //log.info("Detected PEN Drive: " + drive + " - "+ displayName); 
                driveLetter = drive;
                break;
            }
        }

        /*if (driveLetter.equals(""))
        {
            System.out.println("Not found!");
        } 
        else 
        {
            System.out.println(driveLetter);
        }
        */

        //System.out.println(driveLetter);
        return driveLetter;
    }
}

现在的问题是当我运行 external.java (main) 时没有错误。但是,输出仅显示检测到的驱动器是 F:\ 但它没有运行指定的程序 external.exe 并且还提到该程序已终止。有人可以帮我指出我出错的地方以及正确的代码应该是什么样的吗?我是 Java 新手。

我从http://www.snip2code.com/Snippet/506/Detect-USB-removable-drive-in-Java获得了 DetectDrive 代码,我相信它现在正在维护中。

是否可以更改 new FileWriter(" F:\external.bat ") 来检测 USB 驱动器目录?例如,让程序检测 USB 驱动器并自动放入正确的目录,而不是我们手动输入 F:\。我还没有答案。请帮忙!

4

1 回答 1

1

似乎问题出在命令上:

"cmd /c start" +DetectDrive+ "\\external.bat"

它应该有一个{space}后启动:

"cmd /c start " +DetectDrive+ "\\external.bat"
于 2014-07-18T13:37:20.820 回答