在 Java 中从字符串创建文件时添加了奇怪的字符

发布于 2025-01-11 02:51:21 字数 1223 浏览 0 评论 0原文

当尝试在 Java 中创建 bash 脚本(.sh 文件)时,随机字符会添加到文件的开头。

因此,使用 sbatch 命令提交脚本时,该脚本会被 SLURM 拒绝。

我的代码:

String ss = "#!/bin/bash\n"; // script String
        ss+= "#SBATCH --job-name="+scriptJobName+"\n" // scriptJobName is a String that's initialized earlier

try{
    FileOutputStream fos = new FileOutputStream(scriptName); // Where scriptName is a String that is initialized earlier.
    DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
    outStream.writeUTF(ss);
    outStream.close();
}catch(IOException e){
    System.err.println("ERROR: writing sub-job execution script "+e);
}

脚本创建:

#!/bin/bash
#SBATCH --job-name=ColComp

[编者注:生成的脚本的第一行前面有两个不可见的字符,0x05和0x01,似乎只有在编辑时才可见模式,即使格式化为代码。这似乎是“永远不要发布代码图片”的反例:-) 输入图片此处描述]

SLURM 提交错误:

sbatch:错误:这看起来不像批处理脚本。第一个 sbatch:错误:行必须以 # 开头!接下来是通往 口译员。 sbatch:错误:例如:#!/bin/sh

询问

如何防止添加这些不需要的字符? (或自动删除它们 - 在 Java 中)

When trying to create a bash script (.sh file) in Java, random characters are added to the beginning of the file.

As a result, the script is rejected by SLURM when submitted using the sbatch command.

My Code:

String ss = "#!/bin/bash\n"; // script String
        ss+= "#SBATCH --job-name="+scriptJobName+"\n" // scriptJobName is a String that's initialized earlier

try{
    FileOutputStream fos = new FileOutputStream(scriptName); // Where scriptName is a String that is initialized earlier.
    DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
    outStream.writeUTF(ss);
    outStream.close();
}catch(IOException e){
    System.err.println("ERROR: writing sub-job execution script "+e);
}

Script Created:

#!/bin/bash
#SBATCH --job-name=ColComp

[Editor's Note: The first line of the generated script is preceded by two invisible characters, 0x05 and 0x01, which seem to be visible only in edit mode, even when formatted as code. This seems to be the counterexample to "never post pictures of code" :-)
enter image description here
]

SLURM Submission Error:

sbatch: error: This does not look like a batch script. The first
sbatch: error: line must start with #! followed by the path to an
interpreter. sbatch: error: For instance: #!/bin/sh

Asks

How can I prevent these unwanted characters from being added? (or automatically remove them - in Java)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自此以后,行同陌路 2025-01-18 02:51:21

问题是您使用了 DataOutputStream。这里不需要,只需写入FileOutputStream即可。 0x05 0x01 是一个对象标头,仅当稍后由 DataInputStream 读取输出时才有意义。

The problem is you used a DataOutputStream. That is unnecessary here, just write to the FileOutputStream. The 0x05 0x01 is an object header that is meaningful only when the output is read later by a DataInputStream.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文