Java代码从检测到的驱动器运行程序

时间:2014-07-18 13:05:21

标签: java batch-file removable-drive

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

external.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代码,我相信它现在处于维护状态。

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

1 个答案:

答案 0 :(得分:1)

似乎问题在于命令:

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

启动后应该有{space}

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