Skip to content
Advertisement

OutputStream as a method parameter Java [closed]

Reference Codewars Problem: https://www.codewars.com/kata/52dc4688eca89d0f820004c6/java

Context: The java version of this kata sometimes passes an OutputStream and sometimes doesn’t pass one to your solution, which results in needing two methods, public String execute(String code, InputStream input) and public String execute(String code, InputStream input, OutputStream output)

Question: How do you add the data (characters or int) to the output stream that is passed to you? I pass all of the tests except the output stream ones and since the Kata specified that OutputStream is OPTIONAL I am getting very frustrated. Thanks in advance.

Code so far:

public static String execute(String code, InputStream input, OutputStream output) {
        String s = execute(code, input);
        DataOutputStream data = new DataOutputStream(output);
        try {
            data.writeChars(s);
        } catch (IOException ex) {
        }

        return s;
    }
public static String execute(String code, InputStream input) {
        //just pretend this code correctly interprets whitespace and returns the correct thing
}

Advertisement

Answer

Thanks @Tom Hawtin, the task insturctions say:

The Java implementations will support an optional OutputStream for output. If an OutputStream is provided, it should be flushed before and after code execution and filled as code is executed. The output string should be returned in any case.

So assuming a working execute(String, InputStream), like:

public static String execute(String code, InputStream input, OutputStream output) {
    String s = execute(code, input);
    if (outputstream != null) {
      try {
        output.flush(); // !!
        // this part looks ok, but probably better/more efficient ways to copy...
        DataOutputStream data = new DataOutputStream(output);
        data.writeChars(s);
      } catch (IOException ex) {
      }
      finally { //"safest" inside finally..
        try {
         output.flush(); //don't close(), the description sounds quite dstinct!
        } 
        catch (IOException ex) {
        }// end catch
      }// end finally
    }//end if
    return s;
}

Better

  • Make the 2-parameter method more stupid, like:

    public static String execute(String code, InputStream input) {
        return execute(code, input, null);
    }
    
  • therefore make the 3-parameter method:

    • intelligent/correct.

    • null sensitive:

      • filling the outputstream “on the fly”.

      • and still flushing before and after execution.


Refs:

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