如何在 Java 中不使用 println() 方法打印消息?
System 类的 println() 方法接受一个 String 作为参数,并在控制台上打印给定的字符串。
示例
public class PrintData {
public static void main(String args[]) {
System.out.println("Hello how are you");
}
}输出
Hello how are you
此外,您还可以通过多种其他方式在控制台上打印数据,其中一些是:
使用输出流
使用输出流类,您可以将数据写入指定的目标。您可以通过将标准输出流对象 System.out 作为源传递给它们,从而在屏幕/控制台上打印数据。
示例
import java.io.IOException;
import java.io.OutputStreamWriter;
public class PrintData {
public static void main(String args[]) throws IOException {
//Creating a OutputStreamWriter object
OutputStreamWriter streamWriter = new OutputStreamWriter(System.out);
streamWriter.write("Hello welcome to Tutorialspoint . . . . .");
streamWriter.flush();
}
}输出
Hello welcome to Tutorialspoint . . . . .
使用 printf() 和 print() 方法
Java 的 PrintStream 类提供了另外两种方法来在控制台上打印数据(除了 println() 方法)。
print() − 此方法接受任何基本或引用数据类型的单个值作为参数,并在控制台上打印给定的值。
(双精度值或浮点值或整数值或长整数值或字符值、布尔值或字符数组、字符串或数组或对象)
printf() − 此方法接受局部变量、表示所需格式的字符串值、表示参数的可变数量的对象,并根据指示打印数据。
示例
public class PrintData {
public static void main(String args[]) {
System.out.print("Hello how are you");
System.out.printf(" "+"welcome to Tutorialspoint");
}
}输出
Hello how are you Welcome to Tutorialspoint
使用 log4j
log4j 库的 Logger 类提供方法在控制台上打印数据。
依赖项
<dependencies> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.4</version> </dependency> </dependencies>
示例
import java.util.logging.Logger;
public class PrintData{
static Logger log = Logger.getLogger(PrintData.class.getName());
public static void main(String[] args){
log.info("Hello how are you Welcome to Tutorialspoint");
}
}输出
Jun 28, 2019 2:49:25 PM Mypackage.PrintData main INFO: Hello how are you Welcome to Tutorialspoint
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP