Given this code, I am baffled as to why it doesn't print to the console....
engine.compileTemplate(new PrintWriter(System.err));
System.err.flush();
I see nothing on the console. Same problem with System.out too. And yes I verified that the code works by printing to a file successfully.
Try using the constructor with autoflush. You are flushing System.err, not the PrintWriter.
In what context is this code executed?
Really need more info to determine what's going on.
Is your code running in a plugin that you are debugging?
If so, then with "print to the console" - do you mean the console of the same Eclipse instance as your plugin?
For that you would need to do something like:
MessageConsole console = new MessageConsole("My Console", null);
console.activate();
ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[]{ console });
MessageConsoleStream consoleStream = console.newMessageStream();
consoleStream.println("Hello, world!");
Otherwise, it goes to the console where Eclipse was launched.
Read more here: http://wiki.eclipse.org/FAQ_How_do_I_write_to_the_console_from_a_plug-in%3F
Related
I have a program where, during a long task, I use System.out to print messages to indicate its progress. However, this can only be seen in the terminal in Visual Studio Code.
When I export the program to a jar file and double-click it, it doesn't print out any System.out messages, although it is still able to do its tasks.
So, how do I make my program open a terminal upon double-clicking its jar file so that it can print messages to it in a similar manner as using System.out?
You can easily change where stderr and stdout go:
public class RedirectStdStreams {
public static void main(String[] args) throws Exception {
System.setOut( new PrintStream( "/tmp/stdout" ) );
System.setErr( new PrintStream( "/tmp/stderr" ) );
System.out.println( "Look ma, watch me juggle this chainsaw!" );
System.err.println( "Uh oh, that didn't go well at all...");
}
}
Try running with java cli. This is basically what your IDE does when you run your project.
java -jar yourjar.jar
If you don't want to keep your console open and still persist logs, I would suggest using log4j or just simply redirect output of System.out to file
I'm running a test case in debug mode on a new installation of Netbeans 8.2 with a break point on a myId field.
#Test
public void testCreateDocumentSecurityNullRequest() throws Exception {
final Integer myId = 1;
myRequest request = null;
mockMvc.perform(post("/pathTo/apply/" + myId).contentType(contentType).content(json(request)))
.andExpect(jsonPath("$.code", is("400")));
}
I know the test is executed because I see the test results, but the debugger doesn't stop on my break point.
The Debugger Console shows:
Listening on 23206
User program running
LineBreakpoint myTest.java : 'line #' successfully submitted.
User program finished
I don't understand why it's not stopping and just continuing? I tried it in Eclipse and it stops and let's me continue as I would expect. I'm sure I'm just misunderstanding something simple but I read documentation and nothing sticks out to me. I also looked at some other Stack Overflow posts that were similar but those didn't seem to fit my issue.
I had a similar issue. NetBeans 6.5 won't stop on a breakpoint in my code.
I figured that while working with a project I changed source location (was: "project.6.5", I changed it to just "project").
NetBeans remembered the old source location ("project.6.5") which became non-matching as I ran code from "project". A breakpoint was displayed correctly (red square), but won't stop.
I opened Window > Debug > Sources and checked current code ("project"). Breakpoint became a broken square and it wrote in logs about source not matching.
After I unchecked old source ("project.5.6") it started working fine again.
...\AppData\Roaming\NetBeans\8.2\config\Services\org-netbeans-modules-debugger-Settings.properties - remove all 'breakpoint' lines from this file.
I used system("java .....")to run a java app in cmd with VC++ code.
The java app will run a server in the cmd,it will output info in the console.And I can also enter commands to it just like run "dir" commands in cmd.
Now I want get all the output in my program and use C++ code to write commands sent to the java app.
But I found that the system() won't return until I stop the java app.It's reasonable.And how to avoid it?Use Thread ?
And the biggest problem is I don't know how to get the output and write commands,can anyone give me a method?
Thanks a lot!
P.S. The java app's code can't be changed.
--------------------------------------I have made progress--------------------
int main()
{
char psBuffer[256];
FILE* output = _popen("java xxxx.jar", "rt" );
if(output == NULL)
return 0;
while(fgets(psBuffer, 256, output))
{
printf(psBuffer);
}
if (feof( output))
{
printf( "\nProcess returned %d\n", _pclose( output ) );
}
else
{
printf( "Error: Failed to read the pipe to the end.\n");
}
system("pause");
return 0;
}
When I use "dir".It works perfect!But when I use java,psBuffer is always nothing,and the output of java app is normally.Is it pipe cannot redirect java's output?
I change my code and make some java command run perfect:
FILE* output = _popen("java -version 2>&1", "rt" );
But when it run that .jar,It failed.I read the .jar's code and find the output is create by java.util.logging.Logger.info().I'm not familiar with java. How dose the info() work in cmd?
Thanks many!
Finally, I found last code above is work correctly.But origin output of java app haven't been redirect .It will display normally,but buffer is correctly received the output I want.Anyway I solved my problems.Thanks everyone!!!
The MSDN article Creating a Child Process with Redirected Input and Output explains how you can do it. It is quite a lot of code to go through, but will allow you to do what you want, and give you full control over it.
On the other hand, using _popen is much easier, but you don't have as much control. Depends on your exact needs as to how much code you'll be writing :).
How to exit the console of a simple Java program after displaying an error message?
currently my code has:
...
...
if (some condition){
//print error
System.exit();
...
...
But this System.exit(); leaves the console open. I have tried exit(0);, System.exit(0); as well.
If you're wanting to close the Command Prompt window that your application is running in, then I don't believe there is a way to do it (At least not nicely).
Why do you want to start your application from the command prompt and then close the pre-existing Command Prompt window? This will surely get rid of the error message that you're outputting (unless it's also being logged - in which case why print it to a window you want to close?).
This is Windows specific, but would creating a shortcut in Windows Explorer to java -jar MyJarFile.jar or java MyCompiledClass do what you want? Instructions for this sort of approach can be found here.
System.exit(1);
should work fine. Note that if you're exiting with an error, you would normally set a non-zero exit code. From the doc:
The argument serves as a status code; by convention, a nonzero status
code indicates abnormal termination.
This means you can script using common conventions, any process spawning your program can react correspondingly etc.
If I understand you correctly, you want to run your program in a command prompt and if the program fails you want it to display the error message, close the program AND the commad prompt window?
If this is the case then the only thing I could think of would to be to run your program in a batch file that checks the exit status of your program. So in your code write your error message, then I suggest sleep for a few seconds so the user can actually see it, then exit with status code 1.e.g.
if(SomeCondition){
System.err.println("ERROR MESSAGE...");
Thread.sleep(3000);//Sleep for 3 seconds...
System.exit(1);
}
Then run your program from a batch file which checks the "ERRORLEVEL" environment variable e.g.
java <INSERT_PROGRAM_NAME>
IF %ERRORLEVEL% == 1 exit
Hope this helps :)
java.lang.System doesn't have an exit method with no parameters, so System.exit(); would be a compile-error. (System.exit(1);, however, would be fine.) The reason that your code isn't working is probably that you're not recompiling it, so you're still running some old version from before you added that line.
Suppose you are trying to install firefox .bat file from java
public static void main(String[] args) throws InterruptedException {
try {
String[] command = { "cmd.exe", "/C", "Start", "C:\\firefox.bat" };
Runtime.getRuntime().exec(command).waitFor();
}
catch (Exception e)
{
System.out.println("Execution error");
}
}
This would trigger the command prompt and the window will be opened until you manually go and close it after the firefox is installed.
The fix is that in your .bat file just after your command just put an "exit" For eg:
Your firefox.bat would contain
#Start /wait "Firefox" "C:\Firefox Setup 41.0.exe" -ms
exit
This will close your command prompt window. Hope this helps...
have a look at the below link
http://www.cs.bris.ac.uk/jot/decisions/exercise11/exit.html
There is a general convention that a program must return an exit code. The exit code should be zero to indicate success, and non-zero to indicate failure. Platforms differ about what different non-zero codes mean, so programmers often just return 1 as a general indication of failure.
System.exit(); terminates the JVM. The int is the status code (0 means "normal" exit). If it's not exiting it's because that part of your code is not reachable and not being executed at all.
Java API - System.exit()
I have developed a plugin in which a java application is launched.In the console log of this application i want to be notified when new lines added.I have searched internet and found org.eclipse.debug.ui.consoleLineTrackers extention point.I have used it like below.
<extension point="org.eclipse.debug.ui.consoleLineTrackers">
<consoleLineTracker
id="com.plugin.util.MyConsoleTracker"
class="com.plugin.util.MyConsoleTracker"
processType="MyProcessType">
</consoleLineTracker>
</extension>
Then in my java code i have launched application like below.
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classpath);
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH,false);
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,MAIN_CLASS_NAME);
config.setAttribute(IProcess.ATTR_PROCESS_TYPE, "MyProcessType");
ILaunch launch = DebugUITools.buildAndLaunch(config, ILaunchManager.DEBUG_MODE,new NullProgressMonitor());
After these, i can launch my application successfully however my class com.plugin.util.MyConsoleTracker is never called.I cant see any error log either.
can anybody please tell me what i am missing here?
For an example you can see how it is made in m2e-core:
http://git.eclipse.org/c/m2e/m2e-core.git/tree/org.eclipse.m2e.launching/src/org/eclipse/m2e/internal/launch/MavenConsoleLineTracker.java
and
http://git.eclipse.org/c/m2e/m2e-core.git/tree/org.eclipse.m2e.launching/plugin.xml
Methed of YourConsoleLineTrackers should be evoked each time when a new line is showed up in console. Inside Line Tracer you have to distinguish to which process this line belongs to.
Marek