Forcing Eclipse to showing only errors - java

Is it possible to tell Eclipse to show only errors in the console ?
It could be useful as I'm using external libraries that use the output to display unwanted data. I know that there is a button "Show Console when standard error changes", but, I'm looking for a filter rather.
Regards.

Eclipse (the Console view) shows two different outputs: The standard output (System.out) and the error output (System.err). Eclipse itself cannot distinguish between an actual error/exception logged by your programm running, and an external library which writes it copyright/licence information to the error stream.

You can redirect the System.out and/or System.err to another OutputStream using the System.setOut and System.setErr functions. This way you can create your own "Console view" or handle the output yourself. If you implement your custom OutputStream class, you can also send the data to the original OutputStream (original System.out or System.err).
PrintStream oldOut;
oldOut = System.out;
System.setOut(new PrintStream(new OutputStream() {
#Override
public void write(int b) throws IOException {
// handle the "b" or
// send it to old stdout:
oldOut.write(b);
}
}));
// do what you want with the stream and afterwards
System.setOut(oldOut);
Also be aware that it may be a problem if you do it in the UI thread. For me the application always hanged afterwards.
If you redirect these streams you can decide if you will forward it onto the standard output/error.

Related

Redirect "System.out.print" output of a Java program to a txt file

Code for redirecting the print output within the program:
try
{
System.out.println("Print on console");
// Store console print stream.
PrintStream ps_console = System.out;
File file = new File("C:/Users/John/Desktop/compiletest/output" + trialNum + ".txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.out.println("Print in the file !!");
// Set console print stream.
//System.setOut(ps_console);
System.out.println("Console again !!");
}
catch(Exception e)
{
System.out.println("Mission failed, we'll get em next time");
}
This method works fine if it is implemented in the program I want to redirect its output. In my case I want a separate class that will redirect the output of a certain program to a txt file.
If there is a simpler way to complete this task I am greatly inclined to hear.
This seems like a perfect usage example for a logging framework.
SLF4J
Log4J
Java Logging
There are many other libraries you can use. In general it is always preferable to use a separate stream for files - if you must redirect System.out it could be useful to keep the original PrintStream before you change it so that you can still write to the console if you need to:
PrintStream ORIGINAL_SOUT = System.out;
System.setOut(ps);
System.out.println("ABC"); // Uses file
ORIGINAL_SOUT.println("ABC"); // Uses console
A simple usage example of a logging framework (from the first linked library):
private static final Logger logger = LoggerFactory.getLogger(YourClass.class);
logger.debug("A message at DEBUG level");
logger.info("A message at INFO level");
logger.warn("A message at WARN level");
logger.error("A message at ERROR level");
I think you should create Temporary function for holding and storing your data with temporary and then execute your transactions anyway you want. Finally you can store your data wherever you want with permanently. This is the most known method I know. You should check the link for understanding easier.
http://www.daveoncsharp.com/2009/09/how-to-use-temporary-files-in-csharp/
Logging software (such as SLF4J,Log4J etc)is better option.
It has different ways to create file,different file formats, rolling appenders(based on dates/sequence/size), logs based on priorities

How to change back to standard output console?

I tried to PrintStream to a text file for writing a bunch of output to a file.
But after the file is created, I was trying to switch back to the standard output just to continue on with other processes, but I have no idea about doing that switch. Seems like I have to setOut to the standard console, but how do I do that?
Below is the code that I used to output to a text file. Any ideas?
PrintStream out = new PrintStream(fistr);
System.setOut(out);
Thanks.
Why don't you save it before modifying it, so that you can go back?
PrintStream standard = System.out;
PrintStream out = new PrintStream(fistr);
System.setOut(out);
/*
some other stuff
*/
System.setOut(standard);

How to copy the error message from console to file in java? [duplicate]

This question already has answers here:
Java output console error message to file?
(5 answers)
Closed 8 years ago.
PrintStream out = new PrintStream(new FileOutputStream("test2_output.txt"));
System.setOut(out);
This above code is not a correct code.I require this above file should contain error message that is produced in console. So what will be the code to get error message from console and copy that message into a file.
You can redirect the java standard out and standard error to log files. In fact, here is Oracle's (user submitted blog) answer to your question:
https://blogs.oracle.com/nickstephen/entry/java_redirecting_system_out_and
You need to do something like this:
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
The second statement is the key. It changes the value of the supposedly "final" System.out attribute to be the supplied PrintStream value.
I'd just like to add that it is generally a better idea to use a logging subsystem like Log4j, Logback or the standard Java java.util.logging subsystem. These offer such things as fine-grained logging control via runtime configuration files, support for rolling log files, feeds to system logging.
Or, if what you are doing is not "logging", then consider either:
redirecting standard output to a file on the command line, or
changing your application to use an out stream passed as a parameter rather than writing to System.out.
Messing around with (e.g. redirecting) System.out is liable to cause nasty surprises for other code in your JVM that is not expecting this to happen.
You can refer this this code for generate logger file.
Following code create file of size 1 Mb.
File dir1 = new File (".");
String workingDir = dir1.getCanonicalPath();
FileHandler hand = new FileHandler(workingDir+"\\LOGDATA.log",
(1024*1024),3);
Logger logger = Logger.getLogger("LOGDATA");
SimpleFormatter formatter = new SimpleFormatter();
hand.setFormatter(formatter);
logger.addHandler(hand);
logger.info(workingDir+"\\LOGDATA.log");
output :
D:\LOGDATA.log
Use System.setErr(out);
Source: JavaDoc
Regarding launching app in eclipse, there is an option to write to a console and to a file, by selecting "File" checkbox see:

Output redirection in Java

How can I redirect an output in java?
I am running a program in eclipse. My code is as follows:
public static void main(String[] args) throws Exception{
/* Redirect output to file */
File file = new File("fileName");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
OtherClass.main(args);
}
Without the output redirection I wrote above, the code returns some values in black and some in red (which are not errors, but parameters called in OtherClass).
The redirection above writes the text that appeared in black in the eclipse console in my file, but the output in read is written on console and not in my file.
How can I do the contrary and print the red text in my file and not the black one? And why does eclipse use different colors for this output?
How can I do the contrary and print the red text in my file and not the black one?
Instead of redirecting output from standard output (System.out) to file, redirect output from error stream (System.err). In other words instead of
System.setOut(ps);
use
System.setErr(ps);
// ^^^
And why does eclipse use different colors for this output?
So you could see which output comes from System.out (black), and which from System.err (red - which handles printing Exceptions).
Calling System.setOut() redirects stdout, you need to call System.setErr() to redirect stderr - something like,
// System.setOut(ps);
System.setErr(ps); // <-- for std err
Red output in the Eclipse console is text being printed onto the standard error stream (System.err). In order to accomplish that only the text being printed in red is written to the file you need to replace your call to System.setOut(ps); with System.setErr(ps);.

How to build your non-gui Java program into a console program

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!

Categories

Resources