【问题标题】:FileOutputStream not work on scheduled taskFileOutputStream 不适用于计划任务
【发布时间】:2014-04-05 21:59:16
【问题描述】:

我有一个 jar 文件,双击它时可以正常工作,但是当我安排任务运行它时,FileOutputStream 将无法工作。

它可以正确完成其他任务,例如发送电子邮件和连接到路由器,但它不能写入文件。

我提取了给出该错误的最简单的代码:

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());
    }
}

我尝试通过调用运行 jar 的 .bat 文件进行调度,并使用 Launch4j 从 jar 中创建一个 .exe:单击它时一切正常,但是当我从计划任务中调用它时它不会t 写入文件。 (我正在使用 Window7 Professional)

【问题讨论】:

  • 您检查过用户(任务创建者)的权限吗?
  • 我已经在具有所有权限的不同电脑上尝试过...没有任何变化。
  • 您是否看到异常,或者您只是在文件夹中没有看到“TestJar.log”文件?如果是第二个,请确保您查看的是正确的文件夹,因为您没有指定“完整”文件名,并且“当前”文件夹取决于您运行应用程序的方式。或者尝试指定文件的全名。

标签: java windows-7 jar scheduled-tasks fileoutputstream


【解决方案1】:

就像AnatolyG 建议的那样,它可以指定日志的完整路径! (我想知道为什么......但它有效,这就足够了!)

所以,这是一个让上面的代码工作的例子:

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());
}

感谢 AnatolyG!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2020-10-30
    • 2023-03-19
    • 2010-12-04
    • 1970-01-01
    • 2016-07-13
    • 2015-10-11
    相关资源
    最近更新 更多