简体   繁体   English

FileOutputStream在预定任务上不起作用

[英]FileOutputStream not work on scheduled task

I have a jar file that works correctly when double clicking on it, but when I schedule a task for run it, FileOutputStream won't work. 我有一个jar文件,当双击它时可以正常工作,但是当我安排一个任务来运行它时,FileOutputStream将无法工作。

It does correctly other tasks such sending email and connect to router, but it can't write on a file. 它可以正确执行其他任务,例如发送电子邮件并连接到路由器,但不能在文件上写入。

I've extracted the simplest code that gives that error: 我提取了最简单的代码来给出该错误:

package testjar;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestJar {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        FileOutputStream fout = new FileOutputStream("TestJar.log", true);
        fout.write("TestJar ok.".getBytes());
    }
}

I've tried to schedule by calling a .bat file that runs the jar and also to make an .exe from the jar with Launch4j: it does everything well when clicked, but when I call it from scheduled task it doesn't write the file. 我试图通过调用运行该jar的.bat文件进行调度,并使用Launch4j从该jar中创建一个.exe:单击该工具可以很好地完成所有工作,但是当我从计划任务中调用它时,它不会编写文件。 (I'm working on Window7 Professional) (我正在使用Window7 Professional)

Like AnatolyG suggested, it works specifying the full path for the log! 就像AnatolyG建议的一样,它可以为日志指定完整路径! (I wonder why.. but it works, and that's enough!) (我想知道为什么..但是它有效,就足够了!)

So, this is an example to make work the code above: 因此,这是使上面的代码工作的示例:

public static void main(String[] args) throws FileNotFoundException, IOException, URISyntaxException {
    CodeSource codeSource = TestJar.class.getProtectionDomain().getCodeSource();
    File jarFile = new File(codeSource.getLocation().toURI().getPath());
    String jarDir = jarFile.getParentFile().getPath();
    FileOutputStream fout = new FileOutputStream(jarDir+"/JarTest.log", true);
    fout.write(jarDir.getBytes());
}

Thanks AnatolyG! 谢谢AnatolyG!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM