Skip to content

Commit

Permalink
add streamRead with callback
Browse files Browse the repository at this point in the history
add runtime.exec
  • Loading branch information
davidkhala committed Apr 28, 2024
1 parent 66b5ad8 commit 050c7c6
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 16 deletions.
12 changes: 12 additions & 0 deletions src/main/java/davidkhala/common/CLI.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package davidkhala.common;

import java.io.IOException;

public class CLI {
public static void exec(String... command) throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec(command);
p.getInputStream().transferTo(System.out);
p.getErrorStream().transferTo(System.err);
p.waitFor();
}
}
1 change: 0 additions & 1 deletion src/main/java/davidkhala/common/FileTool.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@


import java.io.*;
import java.net.URI;
import java.util.Objects;

public class FileTool {
Expand Down
42 changes: 27 additions & 15 deletions src/main/java/davidkhala/common/Stream.java
Original file line number Diff line number Diff line change
@@ -1,24 +1,36 @@
package davidkhala.common;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;

public class Stream {
public static String read(InputStream is) throws IOException {
int size = is.available();
byte[] buffer = new byte[size];
while (true) {
if (is.read(buffer) < 0) {
break;
}
}
public interface InputCallback {
void onData(int _byte);
}

is.close();
return new String(buffer);
public static String read(InputStream is) throws IOException {
int size = is.available();
byte[] buffer = new byte[size];
while (true) {
if (is.read(buffer) < 0) {
break;
}
}

public static InputStream from(String string) {
return new ByteArrayInputStream(string.getBytes());
is.close();
return new String(buffer);
}

public static void read(InputStream is, InputCallback callback) throws IOException {
while (true) {
int b = is.read();
if (b == -1) {
break;
}
callback.onData(b);
}
}

public static InputStream from(String string) {
return new ByteArrayInputStream(string.getBytes());
}
}
11 changes: 11 additions & 0 deletions src/test/java/CLITest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import davidkhala.common.CLI;
import org.junit.Test;

import java.io.IOException;

public class CLITest {
@Test
public void jVersion() throws IOException, InterruptedException {
CLI.exec("java", "-version");
}
}

0 comments on commit 050c7c6

Please sign in to comment.