java如何打出
Java 打印输出的方法
在 Java 中,打印输出主要通过以下几种方式实现:
System.out.print() 直接打印内容,不换行。例如:
System.out.print("Hello");
System.out.print("World");
输出结果为 HelloWorld。
System.out.println() 打印内容后自动换行。例如:
System.out.println("Hello");
System.out.println("World");
输出结果为:
Hello
World
System.out.printf()
格式化输出,类似于 C 语言的 printf。例如:

int num = 10;
System.out.printf("Number: %d", num);
输出结果为 Number: 10。
String.format() 返回格式化字符串,不直接打印。例如:
String formatted = String.format("Number: %d", num);
System.out.println(formatted);
打印数组或集合内容
Arrays.toString() 打印数组内容:
int[] arr = {1, 2, 3};
System.out.println(Arrays.toString(arr));
输出结果为 [1, 2, 3]。

遍历集合 打印集合内容:
List<String> list = Arrays.asList("A", "B", "C");
for (String s : list) {
System.out.println(s);
}
日志打印
使用日志框架 例如 SLF4J 或 Log4j:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(MyClass.class);
logger.info("This is an info message");
打印异常信息
打印异常堆栈
try {
// 可能抛出异常的代码
} catch (Exception e) {
e.printStackTrace();
}
重定向标准输出
重定向到文件
PrintStream fileOut = new PrintStream("output.txt");
System.setOut(fileOut);
System.out.println("This will go to file");
注意事项
- 在大型应用中,建议使用日志框架而非直接使用
System.out。 - 格式化输出时注意占位符类型匹配(如
%d对应整数,%s对应字符串)。 - 打印对象时默认调用
toString()方法,可重写该方法自定义输出。






