Skip to content
Advertisement

How to read haskell.exe console output in Java?

I need to save Java output to test2.txt file, run through java compiled haskell hello.exe file, get data from tes2.txt, do something with it and then output result to console and read it with Java.

Hello.exe

import System.IO
import Control.Monad
import Data.List

main = do  
    handle <- openFile "test2.txt" ReadMode
    contents <- hGetContents handle
    let sas = words contents
    putStrLn (unwords sas)
    

Java

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        String str = "1 13 23";
        BufferedWriter writer = new BufferedWriter(new FileWriter("C:\Users\dabch\OneDrive\Desktop\chepuch\chich\test2.txt"));
        writer.write(str);

        writer.close();
        Process p = Runtime.getRuntime().exec("C:\Users\dabch\OneDrive\Desktop\chepuch\chich\hello.exe");

        String s;
        System.out.println(p.getOutputStream());
        BufferedReader stdInput = new BufferedReader(new
                InputStreamReader(p.getInputStream()));
        while((s=stdInput.readLine())!=null){
            System.out.println(s);
        }

    }
}

When I run hello.exe by myself, it gives me the right result: 1 13 23.

But when I run hello.exe with Java getRuntime().exec() it gives me: 1 1 1.

How can I fix this?

Advertisement

Answer

The current directory for “hello.exe” is same as the java application which perhaps contains a file called “text2.txt” with contents “1 1 1”. That isn’t same as the file you write which is C:UsersdabchOneDriveDesktopchepuchchichtest2.txt.

Fix by making hello.exe read from C:UsersdabchOneDriveDesktopchepuchchichtest2.txt or change directory for the sub-process hello.exe so it runs from C:UsersdabchOneDriveDesktopchepuchchich:

File exe = new File("C:\Users\dabch\OneDrive\Desktop\chepuch\chich\hello.exe")
Process p = new ProcessBuilder(exe.toString())
                   .directory(exe.getParentFile())
                   .inheritIO().start();

With .inheritIO() you should see the output directly without your loop.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement