5

Can anybody please help me by providing different ways of printing other than System.out.println() statement in Java?

developer
  • 9,116
  • 29
  • 91
  • 150
hari
  • 1,297
  • 5
  • 17
  • 36

7 Answers7

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
  • 1
    It 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");        
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
ponds
  • 2,017
  • 4
  • 16
  • 11
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 solve it in eclipse by placing a mouse on the word a pop-up window will appear scroll down and select JAVA.LANG.SYSTEM .It will fix the problem and your code will run.

Charuක
  • 12,953
  • 5
  • 50
  • 88
james
  • 1
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
0

You can also try the code System.out.printf();