I dont know how to describe it well, but i will try. Ok, i want to be able to build my java program so that when it opens, it will look and work exactly as it does in the console. So it reads the Scanner class and prints normally, and does everything it would do if it was in the console. Ive looked around for this and havent found anything. I can make a gui java program fairly easily, but i would rather have a terminal, console like program, that works exactly as the java console, thanks.
Based on your comment:
but i want to do hundreds of links at
a time which works perfectly using the
scanner nextLine() method, i can just
post 100 or 200 links in the java
console and it will automatically sort
them out.
I'm guessing what you want is batch processing. You can have your 100 or 200 links in a text file, one per line. And then your Java program:
import java.io.*;
public class Batch{
public static void main(String args[]){
try{
FileInputStream fstream = new FileInputStream("sample.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
while((line = br.readLine()) != null){
//Do something with your line
System.out.println(line);
}
in.close();
}catch(IOException ioe){
System.err.println(ioe.getMessage());
}
}
}
You compile this program, open up a console and run it:
java Batch
It reads your sample.txt file and for each line it does something, in this case print it to the console.
You might be looking for the standard input and output members of the java.lang.System class:
class HelloWorld {
public static void main(String... argv) {
System.out.println("Hello, World!");
}
}
For processing input, you can use Scanner on standard input:
Scanner scanner = new Scanner(System.in);
If you want to get really fancy, you can print some of your output to System.err, which is a PrintStream just like System.out.
From the comment, "when i compile my classes i get a jar file, which does nothing when i click on it, which i think is normal because its not gui," I think your problem is an operating system problem (Windows?), not a Java problem.
Windows maps the "Open" action for JAR files to run with javaw.exe, which doesn't create a console. You'll either need to modify the default file association on each machine, or create something like a batch file that overrides this default behavior.
You could write two programs: the first is your actual "console" Java application, and another is just a shell that uses Runtime.exec() to create a Windows console (cmd) and executes the first program within it.
There are also opensource projects (check Sourceforge) that wrap your JAR in a Windows executable.
Use launch4j. It will create a exe of your non GUI application. In launch4j go to header section and check the console option. Done!
Related
I have a command line application (also it's source code in C language). I want to use it in my first android application.
Here are my questions:
I have a compiled executable for mac. Should I recompile it for android? If yes, how?
Is it possible to have a two way communication with an executable in shell in Java/Android?
I'm looking for something like:
Runtime.getRuntime().exec(cmd);
After a lot of googling, that line of code was only thing that I found. But I don't want to close the executable after each call (it communicates with a server on the internet). Here is what I want to do:
1. Open shell executable
2. write AAA
3. read line
4. write BBB
5. read line
6. write CCC
...
98. write XYZ
99. read line
100. close executable
Note that there may be nothing to read, and it shouldn't wait for it.
Yes, you need recompile it with NDK. How: you can find more information on official Android site, where examples also present.
Yes its also possible to do that, and there are two ways exist:
a) JNI. You need to write a wrapper for for you function, and compile a shared library
b) You can compile executable file, run it and communicate via input/output stream. Something like:
try {
Process pb = Runtime.getRuntime().exec(cmd);
String line;
BufferedReader input = new BufferedReader(new InputStreamReader(pb.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println("Input from your C/C++ app: " + line);
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
String str = "";
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
int tempint = 0;
try {
//The program cannot get out from this while loop!
while((tempint = bfr.read()) != -1){
str += Character.toString((char)tempint);
}
}
catch(IOException ioe) {
System.out.println(ioe);
}
//Print the input
System.out.println(str);
This is the code I wrote for reading user's input from standard input. This piece of code is extracted as playinput.jar
And I have written a script play to run this jar. But after I run ./play in terminal(linux) and finish my input, which does not contain enter, I have to press Ctrl+D twice to get the input printed out.
The same problem occurred when I ran another script called check, which will simply invoke ./play and send some input via stdin. After I ran ./check, it just hanged there and the input cannot be printed out.
Could anyone help fix this problem? Thank you:)
That's just how the Linux terminal works. It has nothing to do with your Java code.
If you test it out with a command like cat > textfile, you will find that unless you are at the beginning of a line, ^D doesn't immediately end the file as you might expect it to. (I don't know all the details of this behavior, but that's the gist of it.)
The convention for Linux is that a text file always ends with a newline. You can run into problems like this if you don't follow the convention.
However, I'm not sure about your problem with the program hanging when you send it data using redirection. That part is more surprising to me, since it's not interactive so the terminal behavior shouldn't be an issue.
Whilst building an wrapper for an console application I came across this weird issue where the Input Stream connected to the output (stdout) of the external process is completely blank until the external process exits.
My code as below:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
public class Example{
public static void main(String args[]) throws IOException{
File executable = ...
ProcessBuilder pb = new ProcessBuilder(executable.getCanonicalPath());
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.forName("UTF-8")));
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
}
}
I've tried several variants of reading from the input stream and all resulted in the same behavior.
I've tried:
CharBuffer charBuf = CharBuffer.allocate(1000);
InputStreamReader isr = new InputStreamReader(p.getInputStream(), Charset.forName("UTF-8"));
while(isr.read(charBuf) != -1){
System.out.print(charBuf.flip().toString());
}
and
byte[] buf = new byte[1000];
int r;
while((r = p.getInputStream().read(buf)) != -1){
System.out.print(new String(buf, 0, r));
}
all to no avail.
Somewhere along the line the output from the external process is being buffered (indefinitely) and I can't really figure out where. Loading the process from the command line seems to work fine where I see output coming out instantaneously. The strangest part is where the fact that the termination of the external process results in a flood of all the "buffered" output at once (a lot of stuff).
Unfortunately I don't have access to the source of the external process but given that it writes to stdout fine when in a console shouldn't really make a difference there (as far as I know).
Any ideas are welcome.
Edit:
One answer recommended me to rewrite the reader for the output and error streams to run on a separate thread. My actual implementation is doing that! And yet the problem still exists. The code posted above is a SSCCE of my actual code condensed for readability purposes, the actual code involves a separate thread for reading from the InputStream.
Edit 2:
User FoggyDay seems to have provided the answer which defines how the behavior of output buffering change when outputting between console and non-consoles. Whilst processes which detect that they are writing to a console use line buffering (buffered flushed every new line), writing to non-consoles (everything that it detects to not be a console) may be fully buffered (to a size of something like 8K). If I make the external process spam (8K of lorem ipsum in a for loop) output does indeed appear. I guess my question now is how to make my java program trigger line buffering on the external process.
To your question "how to make my java program trigger line buffering on the external process":
On Linux you can use the "stdbuf" program (coreutils package): stdbuf -oL your_program program_args
You only need to change stdout since stderr is unbuffered by default. The man page of setlinebuf gives additional background information if you're interested: http://linux.die.net/man/3/setlinebuf
Some software checks if it is writing to a terminal and switches behavior to unbuffered output. This could be a reason, why it works in the terminal. Pipe the output to cat and see if the output still appears immediately.
Another reason could be that the program is waiting for input or a close of its stdin before it does something, although this does not really match the symptoms described so far.
I am trying to execute an executable file and a perl script from within a java program. I have found many topics similar to this but most of them refer to windows. I know java is platform independent and it should work anyways but it doesn't. The solution I have tried already is the one based on the java Runtime and it's exec method. It works just fine on windows but since I'm porting my program on linux I need to adapt it. As I said I need to execute an executable file that I have compiled and was written in c++ which it looks like it's working but it finishes executing with an exit value of 1. I have no idea what it means but on windows it exits with 0 and that's how it should be on linux as well (?!?!). The pearl script on the other hand does not start at all. I use the command "perl script.pl" and it exits with a value of 255. Needless to say, it doesn't do what it's supposed to.
Does anybody know another way to execute these files? Or maybe where I am wrong with my implementation?
here's the code if you want to take a look at it:
This is the one for the perl script
public static void main(String[] args){
System.out.println("Starting");
try{
String[] cmd = {"perl", "cloc-1.53.pl"};
Process pr = Runtime.getRuntime().exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exit code: " + exitVal);
} catch (Throwable t){
t.printStackTrace();
}
}
For the compiled file I change this:
String[] cmd = {"perl", "cloc-1.53.pl"};
with:
String cmd = "./UCC";
There should be no differece in starting processes on windows and linux.
Good article http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
Its for the old way but gives good insight.
Article converting to the new way:
From Runtime.exec() to ProcessBuilder
How do you process information in Java that was input from a file. For Example: suppose you have a file input.txt. The contents of this file is:
abcdefghizzzzjklmnop
azzbcdefghijklmnop
My hope would be that the information would be put into the argument array of strings such that the following code would output "abcdefghizzzzjklmnop"
class Test {
public static void main(String[] args) {
System.out.println(args[0]);
}
}
The command I have been using throws an array out of bound exception. This command is:
java Test < input.txt
Non-file based arguments work fine though. ie. java Test hello,a nd java Test < input.txt hello.
More information:
I have tried putting the file contents all on one line to see if \n \r characters may be messing things up. That didn't seem to help.
Also, I can't use the bufferedreader class for this because this is for a program for school, and it has to work with my professors shell script. He went over this during class, but I didn't write it down (or I can't find it).
Any help?
You should be able to read the input data from System.in.
Here's some quick-and-dirty example code. javac Test.java; java Test < Test.java:
class Test
{
public static void main (String[] args)
{
byte[] bytes = new byte[1024];
try
{
while (System.in.available() > 0)
{
int read = System.in.read (bytes, 0, 1024);
System.out.write (bytes, 0, read);
}
} catch (Exception e)
{
e.printStackTrace ();
}
}
}
It seems any time you post a formal question about your problem, you figure it out.
Inputing a file via "< input.txt" inputs it as user input rather than as a command line argument. I realized this shortly after I explained why the bufferedreader class wouldn't work.
Turns out you have to use the buffered reader class.
I'm not sure why you want to pass the contents of a file as command line arguments unless you're doing some weird testbed.
You could write a script that would read your file, generate a temporary script in which the java command is followed by your needs.