Home > Mobile >  How to read haskell.exe console output in Java?
How to read haskell.exe console output in Java?

Time:11-01

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?

CodePudding user response:

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:\Users\dabch\OneDrive\Desktop\chepuch\chich\test2.txt.

Fix by making hello.exe read from C:\Users\dabch\OneDrive\Desktop\chepuch\chich\test2.txt or change directory for the sub-process hello.exe so it runs from C:\Users\dabch\OneDrive\Desktop\chepuch\chich:

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.

  • Related