First of all I regret as I am asking a very basic and peculiar question;But I am new to Java as well as programming. I studied that "out" in system.out.println() is an object of system class.Can "out" be Replaced with any other objects of the system class ? If so what are the members and how???
You can call println() on any PrintStream. If you look at the System javadoc, you will find another PrintStream static field, namely System.err. For example:
System.err.println("This goes to POSIX standard error!");
If you want to actually replace standard out with your own output stream, you can pass your stream to System.setOut(PrintStream) or the corresponding System.setErr(PrintStream)
here are 2 very useful links (hope this helps)
Javapapers: system.out.print
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html
here's a short description of it below :
Structure of System.out.println
Following is the skeletal structure of System.out.println in the JDK source. Through this code snippet the essential parts are highlighted and its given for better understanding.
public final class System {
static PrintStream out;
static PrintStream err;
static InputStream in;
...
}
public class PrintStream extends FilterOutputStream {
//out object is inherited from FilterOutputStream class
public void println() {
...
}
Change out of System.out.println
‘out’ object can be customized. out gets initialized by java runtime environment at startup and it can be changed by developer during execution.
Instead of standard output, in default cases when you run a program through command line, the output is printing in the same command window. We can change that behavior using setOut method as below.
In the following example
public class ChangeOut {
public static void main(String args[]) {
try {
System.setOut(new PrintStream(new FileOutputStream("log.txt")));
System.out.println("Now the output is redirected!");
} catch(Exception e) {}
}
}
Yes
System.setOut(out) does just that.
where out can be any instance of PrintStream.
For example :
System.setOut(System.err); would set the default output stream to be the same as the default error stream.
yes. you can use different key words as System.err.println() or system.in and different , you can get the complete view here http://javapapers.com/core-java/system-out-println/ in this link you can have a complete tutorial thing for you.
Yes, e.g. err
But I would download any of Java IDE (Intellij IDEA or Ecliplse), create a new java project, new class, new main method, type System.out and hit Ctrl + Space and see what happens
Related
Currently, I am trying to read the console output of my program when there is a method call. How it works is, my Java program calls the JNI wrapper to invoke the C++ method call. My C++ is using std::cout. The payload.invoke will invoke my c++ library API. Inside the c++ API there are a few cout statements. That is the statement I want to read it as a variable in Java.
The current PrintStream only supports out, print, println and printf.Each time when there is a method call, there are bunch of logs being printed out in command prompt. Now, I would like my java program to read those output which my C++ prints out.
This is my current Java code:
public void execute() {
try {
Matcher m = Pattern.compile("([^()]*)[(]([^()]*)[)]").matcher(getPayloadString());
m.find();
boolean passed;
if (m.group(2).isEmpty()) {
// this is where it invoke the method
passed = (boolean) payload.invoke(testcase);
System.out.println("Boolean is: " + passed + "\n");
}else {
passed = (boolean) payload.invoke(testcase, ObjectCreator.convertParameters(m.group(2)));
System.out.println("Boolean2 is: " + passed + "\n");
}
String output = passed ? "PASS" : "FAIL";
// I want to use the console output string variable here -> xxxx
TestCase.printResult(payload.getName(), output, m.group(2), xxxx, "");
} catch (Exception ex) {
ex.printStackTrace();
}
}
Are there any ways to do it? Previously I tried using one of the tutorial from here. but that seems not working. Can someone help me out with this please. Thanks in advance.
If you have full control of the .cpp codebase it is possible for you to change the std::cout to become a ostream& instead.
By referencing a base class you can easily switch the implementation.
Do a JNI-Stream whichh extends the ostream& and just overwrite the operators you need to send JNI wrapped callbacks to java.
Then depending on if you run native or Java style use your JNI-Stream instead of the std::cout.
I would do something as seen in the link below to package and send the data to Java:
JNI - How to callback from C++ or C to Java?
that is my 2 cents.
Read carefully the JNI tutorial.
https://www.baeldung.com/jni
Follow the tutorial.
Basically you need to create a java class with a static block to load the C++ library:
static {
System.loadLibrary("native");
}
Then you can create your own static java method and invoke a method on the library.
If what you need is read the output from a system call, it's a different matter.
This can help you:
Java Runtime.getRuntime(): getting output from executing a command line program
I was doing some work for college and my main runs this:
Spreadsheet sheet = new Spreadsheet(0,0);
SpreadsheetManager manager = new SpreadsheetManager(sheet);
/* Read an Import file, if any */
String filename = System.getProperty("import");
if (filename != null)
sheet.parseInputFile(filename, sheet);
Thing is, when I actually try to import a file it doesn't do what is supposed to and the filename is always null, so it never reaches my parseInputFile.
My teachers made a bunch of code for different programming exercises that do similar things available, and I've also looked at projects my colleagues did in previous years, but every single one does what I am doing above.
I have to run my program like this: java -Dimport=A-002-002-M-ok.import calc.textui.Calc otherwise none of the tests given by the teachers will run.
I'm sorry if this is not a useful question, but I've tried looking everywhere. If anyone could explain how the System.getProperty("import") works and why it isn't working in this case, I would be very grateful.
I suggest you take a look at the documentation of System.getProperty().
Basically it retrieves a value from the system, either already present or set by you.
To avoid retrieving null you can use another method signature that specify a default value:
System.getProperty("import", "file.txt");
To set a System property, you can specify it at launch:
java -Dimport="file.txt" your_application
or set it programatically :
System.setProperty("import", "file.txt");
When you run your program with:
java -Dimport=foo
then the method call
System.getProperty("import")
should return "foo".
Is ist possible that you write a tiny example program to convince yourself? Without any SheetManagers and all stuff, just
class ItWorks {
public static void main(String[] args) {
System.out.println(System.getProperty("import"));
}
}
Call it thus
java -Dimport=indeed ItWorks
and report what happens.
That being said: if you want to pass command line arguments, why don't you use the facility for command line arguments? (i.e. the String[] array passed to main?)
You could then call your program like this:
java calc.textui.Calc my-nice-spreadsheet.data
=====================================================
Please write the follwoing in your calc.textui.Calc program immediately after the open brace of your class definition:
public class Calc ..... { // a line like this already exists
// insert next line here
public static String filename = System.getProperty("import");
// rest of your class, as before.
}
Then comment out the getProperty() line in your method that didn't work, but leave the rest including the System.out.println(filename);
Does it change?
Maybe system properties are not the most indicated way to do that (depends on your application).
You could also use command line arguments to pass the file name to your main method:
public class CommandLineExample {
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("usage: CommandLineExample <filename>");
System.exit(1);
}
String filename = args[0];
if (filename !=null && !filename.isEmpty()) {
...
}
}
}
Your program should be called as:
java CommandLineExample theFileName
the string "theFileName" will be passed to the main method in args[0] (any additional words will be passed in subsequent positions of args {args[1], args[2], ...})
EDIT
if the program must be called with
java -Dimport=filename ...
then System.getProperty("import") will return the filename.
Confirm that you are calling the correct program (class name, package, version, last compile was successful, ...) and also check that the property is not mistyped like java -Dinport=A-... or has additional spaces, uppercase letters...
I am new to ExpectJ Java programming. I downloaded jar's and able to do few send() and expect() methods. send() would fire a command on console and expect() would identify any prompt's so inputs can be provided. Expect only reads is there are prompts, and not other info. For example, if want to fire, spawn.send("ls") and get list of all file names and so certain action, is that possible?.
Is there way so I can read normal output of spawn.send("ls") for example, without expect which only captures prompts?
You can indeed capture the output stream:
It is one of the methods of the ExpectJ.Spawn class
I am also very new to Java, but I got the output, however, I am still struggling on getting the prompt recognized as I get extra control characters from Unix so do not trust what comes after the second System.out.println (the sh,expect part)
the output works fine, just set it in a variable if you want, or if you use swing, send it to a textarea with a listener.
BTW! if you know how to do the expect without these bloody control characters, 1m,34 [001 and so on, I welcome your input
import expectj.ExpectJ;
import expectj.Spawn;
public class myExpectinator {
public myExpectinator(){
}
public void connect(){
try {
ExpectJ ex = new ExpectJ(10);
Spawn sh = ex.spawn("10.10.10.10", 22, "name", "password");
System.out.println(sh.getCurrentStandardOutContents());
System.out.println(sh.getCurrentStandardErrContents());
sh.expect("~ $");
sh.send("ps\n");
System.out.println(sh.getCurrentStandardOutContents());
//sh.expectClose();
sh.stop();
}
catch(Exception e) {
System.out.println(e);
}
}
}
Edit 2 After recieving a response from Mathworks support I've answered the question myself. In brief, there is an options class MWComponentOptions that is passed to the exported class when instantiated. This can, among other things, specify unique print streams for error output and regular output (i.e. from disp()-liked functions). Thanks for all the responses none the less :)
====================================================================
Just a quick question - is there any way to prevent MATLAB code from outputting to the Java console with disp (and similar) functions once compiled? What is useful debugging information in MATLAB quickly becomes annoying extra text in the Java logs.
The compilation tool I'm using is MATLAB Compiler (which I think is not the same as MATLAB Builder JA, but I might be wrong). I can't find any good documentation on the mcc command so am not sure if there are any options for this.
Of course if this is impossible and a direct consequence of the compiler converting all MATLAB code to its Java equivalent then that's completely understandable.
Thanks in advance
Edit This will also be useful to handle error reporting on the Java side alone - currently all MATLAB errors are sent to the console regardless of whether they are caught or not.
The isdeployed function returns true if run in a deployed application (with e.g. MATLAB Compiler or Builder JA) and false when running in live MATLAB.
You can surround your disp statements with an if isdeployed block.
I heard back from a request to Mathworks support, and they provided the following solution:
When creating whatever class has been exported, you can specify an MWComponentOptions object. This is poorly documented in R2012b, but for what I wanted the following example would work:
MWComponentOptions options = new MWComponentOptions();
PrintStream o = new PrintStream(new File("MATLAB log.log"));
options.setPrintStream(o); // send all standard dips() output to a log file
// the following ignores all error output (this will be caught by Java exception handling anyway)
options.setErrorStream((java.io.PrintStream)null);
// instantiate and use the exported class
myClass obj = new myClass(options);
obj.myMatlabFunction();
// etc...
Update
In case anyone does want to suppress all output, casing null to java.io.PrintStream ended up causing a NullPointerException in deployment. A better way to suppress all output is use to create a dummy print stream, something like:
PrintStream dummy = new PrintStream(new OutputStream() {
public void close() {}
public void flush() {}
public void write(byte[] b) {}
public void write(byte[] b, int off, int len) {}
public void write(int b) {}
} );
Then use
options.setErrorStream(dummy);
Hope this helps :)
Another possible hack if you have a stand-alone application and don't want to bother with classes at all:
Use evalc and deploy your func name during compile:
function my_wrap()
evalc('my_orig_func(''input_var'')');
end
And compile like
mcc -m my_wrap my_orig_func <...>
Well, it is obviously yet another hack.
I was doing my academic project and while building and testing i have put many println() statements.
But when I had to submit all prints should not be displayed.
Can i implement something like listener which will be invoked when System.out is tried to be executed and prevents it from displaying.
I dont know how feasible this idea is but just want to know whether its possible or not.
I know i could have used a log file or write into a file but again its just a thought came into my mind if I have to disable SOP how can i do it ..
thanks
use System.setOut function (and setErr)
The following program will only print 1: (and not 2)
public static void main(String[] args) throws FileNotFoundException {
System.out.println("1");
System.setOut(new PrintStream(new OutputStream() {
#Override
public void write(int arg0) throws IOException {
// TODO Auto-generated method stub
}
}));
System.out.println("2");
}
The correct thing to do is to either use flags before printlns, or better yet, to use a Logger (there are many versions available).
It is, however, possible to reroute all System.out away. Search for "redirect system.out" and you will find plenty of examples.
Use log4j. This will allow you to do something like:
if (log.isLoggingEnabled()) {
log.debug("this will be printed at runtime with debugging enabled");
}
You can then configure your application not to print debug statements after you submit your code (this is generally done in either a .properties file or an XML file). using a logger is a very common practice on websites running with Java and there is quite a bit of documentation on log4j in particular out there. In fact, submitting code with System.out lines for debugging is considered bad form in most circles. Think of the person reading the logfiles!
There is a TINY hit to performance to the extra method invocation using the logger, but doing this will make maintainability much more practical. You'd probably impress your instructor too :)
It's generally not a good idea to hard-code writing to System.out. As a quick fix, you could change all references to System.out to your own static variable in one of your classes. This at least gives you the opportunity to change the stream you are writing to. E.g.
public static void main(String[] args)
{
static public PringStream out = System.out;
void someMethod()
{
out.println("some logging message");
}
}
You could quickly replace all uses of System.out in your code with Myclass.out. With this in place, you can then change the output stream according to arguments, or system properties. E.g.
if (Boolean.getBoolean("debug"))
out = System.out;
else
out = new PrintStream(new OutputStream() {
public void write(int data) throws IOException {}
};
Of course, this is all seat-of-the-pants stuff and throwaway code.
A more robust and flexible solution is to use a logging api, like slf4j.
PrintStream realOut = System.out;
try {
out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
System.out.println("bla");
} finally {
System.setOut(realOut);
}
System.out.println(out);