Can anybody please help me by providing different ways of printing other than System.out.println() statement in Java?
Asked
Active
Viewed 1.9k times
5
-
3But still printing to stdout? Why are you trying to avoid System.out.println? – Jon Skeet May 10 '11 at 05:31
-
I just want to learn the different ways.Is it possible to use a file? – hari May 10 '11 at 05:34
-
Also,can't i use a properties file? – hari May 10 '11 at 06:10
-
You can read/write to a file (including properties files) but that is an unrelated question really. – Peter Lawrey May 10 '11 at 07:46
7 Answers
8
import org.apache.log4j.Logger;
....
public class example{
static Logger log = Logger.getLogger(this.class);
.....
public void test(){
String hello ="Hello World";
log.trace(hello);
}
....
}
output will be :
TRACE:(<classname>){2011-10-38-06:644} Hello World 2011-05-10 08:38:06,644

Georgian Citizen
- 3,727
- 6
- 38
- 46
-
1It should be noted that, for this to work, your project has a dependency on Log4j, and `log4j.properties` has to be properly configured. – darioo May 10 '11 at 05:53
-
you must add log4j-1.2.14.jar to your project if you can't find this jar file, type your email here i will send it to your email – Georgian Citizen May 10 '11 at 07:28
4
This may help you.
import java.io.*;
class Redirection {
public static void main(String args[]) throws IOException {
PrintStream pos = new PrintStream(new FileOutputStream("applic.log"));
PrintStream oldstream=System.out;
System.out.println("Message 1 appears on console");
System.setOut(pos);
System.out.println("Message 2 appears on file");
System.out.println("Message 3 appears on file");
System.out.println("Message 4 appears on file");
System.setOut(oldstream);
System.out.println("Message 5 appears on console");
System.out.println("Message 6 appears on console");
}
}
4
Alternate printing methods:
System.out.print("message\r\n");
System.out.printf("%s %d", "message" , 101); // Since 1.5
You can also use regular IO File operations by using special files based on the platform to output stuff on the console:
PrintWriter pw = new PrintWriter("con"); // Windows
PrintWriter pw = new PrintWriter("/dev/tty"); // *nix
pw.println("op");

Raze
- 2,175
- 14
- 30
2
System.err.println() for printing on console. or create your own printstream object and then print to file, database or console.

sudmong
- 2,036
- 13
- 12
0
You can try the following alternatives:
1.
System.err.print("Custom Error Message");
2.
System.console().writer().println("Hello World");
3.
System.out.write("www.stackoverflow.com \n".getBytes());
4.
System.out.format("%s", "www.stackoverflow.com \n");
5.
PrintStream myout = new PrintStream(new FileOutputStream(FileDescriptor.out));
myout.print("www.stackoverflow.com \n");

Pang
- 9,564
- 146
- 81
- 122

Mohit Arora
- 1
- 1