hoijui / Jawk

Java AWK interpreter/compiler
GNU General Public License v3.0
39 stars 23 forks source link

Setting output file #8

Open dariober opened 7 years ago

dariober commented 7 years ago

Hello- I've started using jawk as a library within a Java program. Thanks for making it available.

What I'm trying to do should be pretty standard: Read a file as InputStream, parse it through jawk, collect the output from jawk. The problem is that the output of jawk seems to go to stdout instead of to the file I set.

This is what I'm doing:

@Test
public void testAwk() throws Exception{

    InputStream is= new FileInputStream("test_data/hg19_genes_head.gtf"); // File to parse

    String[] args= {"-F", "\t", "NR < 10"}; // Trivial awk script

    AwkParameters parameters = new AwkParameters(Main.class, null);
    AwkSettings settings = parameters.parseCommandLineArguments(args);

    settings.setInput(is); 
    settings.setOutputFilename("/tmp/foo.txt"); // Here is where I expect the output to go.

    Awk awk= new Awk();
    awk.invoke(settings);
}

When I execute testAwk() I see the first ten lines of the input file printed to stdout and the supposed output file "/tmp/foo.txt" is not even created.

I also tried setting the output file in the awk script: String[] args= {"-o", "/tmp/foo.txt", "-F", "\t", "NR < 10"} and I got the same result.

In either case the output of settings.getOutputFilename(null) is "/tmp/foo.txt".

What am I doing wrong? And more in general, is the above the recommended strategy to use jawk as a library in a Java program?

Many thanks!

Dario

dariober commented 7 years ago

I think I figured it out and I think I was quite off-track before... For first, settings.getOutputFilename() and the -o are not relevant to capture the output of jawk. Secondly, use class Main instead of class Awk.

This example work as I wanted. It writes the stdout of jawk to a given destination file by redirecting System.out to the desired file. Once jawk has terminated, reset System.out to its original state:

@Test
public void testAwk() throws Exception{

    InputStream is= new FileInputStream("test_data/hg19_genes_head.gtf"); // Input file to parse

    String[] args= {"-F", "\t", "NR < 10"}; // Trivial awk script

    PrintStream stdout = System.out;
    try{
        PrintStream os= new PrintStream("/tmp/output.txt"); // Redirect stdout to this file
        new org.jawk.Main(args, is, os, System.err);
    } finally {
        System.setOut(stdout); // Reset stdout to original stream.
        is.close();         
    }
}

I'm still not sure whether there are better ways but this works fine for me (Maybe nice to add it to the readme as example?)

Dario