0

I am using Java to create a file with some data in it. But I encouter a problem. Indeed I succeed in creating a file and write "hello" in it when I run from Eclipse. But when I export that code in a jar file and I tried to execute it in the command line (java -jar myappli.jar), the file is not created. I don't understand why.

Here is my java file which is quite simply.

If you have any answers I would be happy to have it :) Thank you.

package testjar;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class Main {
public static void main(String[] args)
{
    FileOutputStream f = null;
    try
    {
        f = new FileOutputStream(new File("Export_XML.xml"));
        System.setOut(new PrintStream(f));
        System.out.println("hello");
    }
    catch(java.io.IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
                if(f!=null)
                        f.close();
        }
        catch(IOException e) {e.printStackTrace();}
    }
}
}
Burkhard
  • 14,596
  • 22
  • 87
  • 108
nyko29
  • 1
  • 2
    Do you get an Exception when running it on the command line? How do you run it? Any compile warnings? – Burkhard Oct 01 '14 at 16:35
  • Are you running it from the command line? If not, you should be doing this. If so, what error messages, if any, are you getting? – ControlAltDel Oct 01 '14 at 16:36

2 Answers2

0

If you're not getting exceptions, it is most likely being created. The difference is the working directory. Since you're not specifying an absolute path when calling new File the JVM will create the file in the current working directory for the JVM. This is likely different when you're running from the jar vs where it is when you run from Eclipse.

Chris
  • 22,923
  • 4
  • 56
  • 50
0

I cannot see what is specifically wrong, but try making the new File('Export_XML.xml') into its own variable, then doing xmlFile.createNewFile(); Also, I discourage the use of System.setOut() as your program isn't the only part of Java to use it.

dodo
  • 156
  • 10