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

Weird Characters Added When Creating File From String In Java

尝试在 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,这两个字符似乎只在编辑模式下可见,即使格式化为代码也是如此。这似乎是“从不 post 代码图片”的反例:-) ]

SLURM 提交错误:

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

询问

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

问题是您使用了 DataOutputStream。这里不用说了,直接写到FileOutputStream即可。 0x05 0x01 是一个 object header,仅当稍后由 DataInputStream.

读取输出时才有意义