无法使用java类访问和运行批处理文件命令

无法使用java类访问和运行批处理文件命令,java,batch-file,cmd,Java,Batch File,Cmd,我创建了一个java类来执行桌面中的批处理文件,以便批处理文件中的命令也将被执行。问题是,我一直得到错误: 文件名、目录名或卷标语法不正确。 文件名、目录名或卷标语法不正确 我已经检查了.bat名称和目录。这是正确的。当我键入cmd/c start c:/Users/attsuap1/Desktop时,windows资源管理器会打开“桌面”选项卡。但是,当我键入cmd/c start c:/Users/attsuap1/Desktop/DraftBatchFile.bat时,它会给出错误。我的D

我创建了一个java类来执行桌面中的批处理文件,以便批处理文件中的命令也将被执行。问题是,我一直得到错误:

文件名、目录名或卷标语法不正确。 文件名、目录名或卷标语法不正确

我已经检查了.bat名称和目录。这是正确的。当我键入
cmd/c start c:/Users/attsuap1/Desktop
时,windows资源管理器会打开“桌面”选项卡。但是,当我键入
cmd/c start c:/Users/attsuap1/Desktop/DraftBatchFile.bat
时,它会给出错误。我的DraftBatchFile.bat在我的桌面上

以下是我的java代码:

public class OpenDraftBatchFile{
public OpenDraftBatchFile() {
    super();
}

/**Main Method
 * @param args
 */
public static void main(String[] args) {
    //Get Runtime object
    Runtime runtime = Runtime.getRuntime();
    try {
        //Pass string in this format to open Batch file
        runtime.exec("cmd /c start C:/Users/attsuap1/Desktop/DraftBatchFile.bat");
    } catch (IOException e) {
        System.out.println(e);
    }
}
为什么即使目录正确也无法执行批处理文件?有人请帮帮我。非常感谢你

这些是DraftBatchFile.bat中的代码

@echo关闭
echo.>“桌面:\testing\draft.txt”
@echo将文本写入draft.txt>桌面:\testing\draft.txt


当我通过运行java类执行DraftBatchFile.bat时,我希望在我创建的测试文件夹(在桌面中)中创建一个draft.txt文件。

没有桌面:\

相反,试试这样的方法

@echo off
echo . %userprofile%\Desktop\testing\dblank.txt
@echo Writing text to draft.txt > %userprofile%\Desktop\testing\dblank.txt

您只需要更改一个目录,如果它不存在,则创建新的子目录。我的报价是change.bat文件,如下所示:

@echo off
if not exist "%userprofile%\Desktop\testing" mkdir "%userprofile%\Desktop\testing"
echo.>"%userprofile%\Desktop\draft.txt"
@echo Writing text to draft.txt>"%userprofile%\Desktop\draft.txt"
您还可以通过Java代码创建.txt文件并在其中写入文本:

    File directory = new File(System.getProperty("user.home")+"//Desktop//testing");
    if (!directory.exists())
         directory.mkdirs();
    String content = "Writing text to draft.txt";
    File file = new File(System.getProperty("user.home")+"//Desktop//testing//draft.txt");
    BufferedWriter writer = null;
    try {
        writer = new BufferedWriter(new FileWriter(file));
        writer.write(content);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

检查PATH环境变量。请参阅更改路径的链接嗨,谢谢您的帮助。应该向Path环境中添加什么?Java Path目录,C:\Program Files\Java\jdk1.7.0\U 67\binI已设置that@YevhenDanchenko根据我下面的回答,最好使用
%userprofile%\Desktop
,因为如果在其他系统上运行,用户
attsuap
将不存在,我仍然会得到错误
文件名,目录名或卷标语法不正确。
我不知道为什么:(我编辑了批处理文件。我编辑了
runtime.exec(“cmd/c start%userprofile%/Desktop/DraftBatchFile.bat”)
我的java类中的那行代码,但是当我运行java类时,我仍然没有得到我想要的,它仍然会出错。我希望在我在桌面上创建的测试文件夹中创建draft.txt文件。实际上,我只需证明,当我运行java类时,我的批处理文件正在执行。还有其他更简单的命令吗我可以把我的批处理文件放进去证明这一点吗?我将创建一个新的批处理文件,然后再试一次out@SushaNaidu请现在尝试我的批处理代码,我编辑了我的答案,我忘记更换桌面:\part in the first echo.IT WORKED!非常感谢!:)