logo
down
shadow

Copying InputStream to OutputStream halts unless I also write to System.out


Copying InputStream to OutputStream halts unless I also write to System.out

By : user7455107
Date : November 21 2020, 03:00 PM
fixed the issue. Will look into that further As EJP suggested, I split the copying of the streams into separate threads via an executor, then I make sure to close them upon completion of the spawned process:
code :
public int runModule(OutputStream moduleOut, int argShowRange, List<String> arguments) throws IOException {

    int status = -1;
    Logger logger = Util.getOutputStreamLogger(moduleOut);
    logger.info("Starting module {}", getModuleName());

    ProcessBuilder exec = new ProcessBuilder();
    exec.directory(getWorkingDirectory());
    if (configureEnvironment(exec.environment(), moduleOut)) {

        List<String> command = getExecutable();
        command.addAll(arguments);
        exec.command(command);

        logger.info("With PYTHONPATH: {}", exec.environment().get("PYTHONPATH"));
        logger.info("In: {}", getWorkingDirectory());
        logger.info("Executing: {}", StringUtils.join(command, " "));
        Process proc = exec.start();

        try (InputStream procOut = proc.getInputStream(); InputStream procErrOut = proc.getErrorStream()) {
            copy(procOut, moduleOut);
            copy(procErrOut, moduleOut);
            LOGGER.debug("Waiting for process to finish");
            status = proc.waitFor();
            LOGGER.debug("Closing streams");
            procOut.close();
            procErrOut.close();
            logger.info("The process finished with exit code: {}", status);
        } catch (InterruptedException e) {
            LOGGER.warn("The thread was interrupted", e);
            Thread.currentThread().interrupt();
        }
    } else {
        logger.info("Module configuration failed");
    }
    Util.detachOutputStreamFromLogger(logger);

    return status;
}

public void copy(final InputStream in, final OutputStream out) throws IOException {
    executor.execute(() -> {
        try {
            byte[] buffer = new byte[4096];
            int n = 0;
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
        } catch (IOException e) {
            LOGGER.error("Ya done goofed", e);
        }
    });
}


Share : facebook icon twitter icon
Easy way to write contents of a Java InputStream to an OutputStream

Easy way to write contents of a Java InputStream to an OutputStream


By : bobmcleod
Date : March 29 2020, 07:55 AM
seems to work fine Java 9
Since Java 9, InputStream provides a method called transferTo with the following signature:
code :
public long transferTo(OutputStream out) throws IOException
input.transferTo(output);
when write of OutputStream write bytes(internally), then why read of InputStream returns int?

when write of OutputStream write bytes(internally), then why read of InputStream returns int?


By : mohanraj
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Read returns an int so that it can also indicate the end of the stream, as -1. If the signature were
code :
byte read()
Better way of copying InputStream to OutputStream

Better way of copying InputStream to OutputStream


By : Serry Abdelrahman
Date : March 29 2020, 07:55 AM
will help you You can't get away without a buffer with streams, unless you want to copy a byte at a time, which isn't efficient unless you know there are buffered streams in the stack for both input and output.
You can't use ByteBuffers with streams. You can use them with channels, and you can get channels from streams, but all you're doing is adding extra layers over the streams API. You're better off confronting it direct, as below. In the case of network streams, the performance is dominated by the network, not by the code, in any case.
code :
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}
Java: Write to OutputStream and then use it as InputStream

Java: Write to OutputStream and then use it as InputStream


By : mümin gök
Date : March 29 2020, 07:55 AM
may help you . I want to get a file from a remote storage as an InputStream without saving it to the local File System. The remote storage provides a Java API with a method that takes an OutputStream and dumps the file data into it. , Two options:
Memory
Java inputstream/outputstream write to file with same name

Java inputstream/outputstream write to file with same name


By : sh.F
Date : March 29 2020, 07:55 AM
will help you If you'd prefer not to use the popular temporary-file approach, then you can always just read in the whole file, then write back to it afterwards.
Here's a straight-forward implementation.
code :
public static void addRootTag(File xml) throws IOException {
    final List<String> lines = new ArrayList<>();;
    try (Scanner in = new Scanner(xml)) {
        while (in.hasNextLine())
            lines.add(in.nextLine());
    }

    try (PrintStream out = new PrintStream(xml)) {
        out.println("<root>");
        for (String line : lines) {
            // indentation, if you want
            out.print("    ");
            out.println(line);
        }
        out.println("</root>");
    }
}
Related Posts Related Posts :
  • SpringBoot : No matching bean found exception
  • Implementing the Clonable interface, but don't have to override the clone() method
  • how can i get this code to choose a random word once from each array to print a sentence?
  • Static class to get connections from connection pool
  • Unable to start Chrome browser with user profile in Selenium
  • How to pass a object to be created as a parameter for a method in Java?
  • How to retry with hystrix
  • Loading key to KeyStore fails on Android Oreo
  • Spring+Velocity unsuccessful attempts to save object
  • Private constructor in Kotlin
  • Jetty:run fails with NoSuchMethodError with Spring 5
  • Cannot upload my Web Applicartion in Jboss7 EAP7 EAP
  • How to load a certificate from "Credential storage"?
  • Call Genexus procedure stub in Java environment
  • JavaFX clipping produces a 'lottery scratch ticket'-Effect
  • Using DateTimeFormatter on january first cause an invalid year value
  • Get all the output from Watson conversation using java
  • Java unable to open main class and jar file
  • How to override @override method from activity into another class
  • Adding Runtime VM parameters to intellij for Java 9
  • Java IBM MQ Client connected but not getting messages from queue
  • Questions of Tomcat SSL configuration
  • Stale JNLP files for <extension> (since Java 9?)
  • Properly set (system) properties in JUnit 5
  • Spring MVC Model within POST Method is empty
  • VSTS buildagent: Java 9
  • java.lang.NumberFormatException: For input string: "id" for Hibernate
  • Query id return type
  • Pass variable in API url in java .
  • Reading semicolon delimited csv
  • Get the workspace root
  • Native mmap error
  • hashmap and multiple txt files java
  • Kotlin: Access nested enum class from java
  • Google RateLimiter not Working for counter
  • Spring Boot Application Hanging When Running on Command Line
  • large amount of if else refactor
  • Unable to add xmlunit as dependancy in my pom
  • Scanner input needed twice, when only wanted once
  • How to interpret and translate kotlin code to java?
  • Firebase authentication: signInWithEmailAndPassword method dont respond at all
  • How Remove Recycler Separator/divider programmatically or using xml property
  • Not Able to Save Data Hibernate
  • Toolbar addView not working
  • Freeing memory wrapped with NewDirectByteBuffer
  • Synchronization with implicitwait() do not work, why?
  • Wrapper around Java primitive types
  • ClassNotFoundException: spark.Request when running from command line
  • Exception in Hibernate Configuration
  • How can I validate XML embedded in JSON using Citrus framework?
  • How is the String value passed to the updateText() method?
  • Memory efficient replace functions
  • Upload Photo with onActivityResult, but without Fullscreen capturing
  • Docker: Java 8 installation failing on Ubuntu
  • Java Netbeans Calculator performing wrong calculation
  • Nifi: Threads in nifi
  • While loop Int return inside the method completely dead
  • Checking if a user's entry is an integer using try catch statements
  • Forcing a subclass to provide an initialization method
  • calling a fuction and variables from another class in java
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org