Question

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.

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. (I'm working on Window7 Professional)

Was it helpful?

Solution

Like AnatolyG suggested, it works specifying the full path for the log! (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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top