Java StackTraceElement getFileName() 方法



描述

Java StackTraceElement getFileName() 方法返回包含此堆栈跟踪元素表示的执行点的源文件的名称。

声明

以下是 Java StackTraceElement getFileName() 方法的声明

public String getFileName()

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

参数

返回值

此方法返回包含此堆栈跟踪元素表示的执行点的文件的名称,如果此信息不可用,则返回 null。

异常

示例:使用 StackTraceElement 获取当前线程文件名

以下示例演示了 Java StackTraceElement getFileName() 方法的使用。在此程序中,我们定义了一个名为 function2() 的函数,该函数从当前线程的 StackTraceElement 获取文件名。另一个名为 function1() 的函数用于实例化 StackTraceElementDemo 类并调用 function2() 方法。在 main 方法中,我们调用了 function1() 方法并打印结果。

Open Compiler
package com.tutorialspoint; public class StackTraceElementDemo { // main method public static void main(String[] args) { // call function1() to invoke function2() function1(); } // function1() is to invoke function2() // using StackTraceElementDemo object public static void function1() { new StackTraceElementDemo().function2(); } // print the file name of current thread using StackTraceElement public void function2() { System.out.print("File name : "); System.out.print(Thread.currentThread().getStackTrace()[1]. getFileName()); } }

输出

让我们编译并运行上述程序,这将产生以下结果:

File name : StackTraceElementDemo.java

示例:使用 ArithmeticException 的 StackTraceElement 获取文件名

以下示例演示了 Java StackTraceElement getFileName() 方法的使用。在 main 方法中,我们创建了三个 int 变量,其中一个变量的值为零。在 try-catch 块中,我们创建了一个除以零的情况以引发 ArithmeticException。在 catch 块中,我们处理了 ArithmeticException,使用 getStackTrace() 方法从中检索了一个 StackTraceElement 数组,然后在数组的第一个元素上使用 getFileName() 方法,打印文件名。

Open Compiler
package com.tutorialspoint; public class StackTraceElementDemo { public static void main(String[] args) { // variables to store int values int a = 0, b = 1, c; try { // being divide by zero, this line will throw an ArithmeticException c = b / a; }catch(ArithmeticException e) { // get the array of StackTraceElement StackTraceElement[] stackTraceElements = e.getStackTrace(); // print the file name System.out.println(stackTraceElements[0].getFileName()); } } }

输出

让我们编译并运行上述程序,这将产生以下结果:

StackTraceElementDemo.java

示例:使用 Exception 的 StackTraceElement 获取文件名

以下示例演示了 Java StackTraceElement getFileName() 方法的使用。在 main 方法中,我们创建了三个 int 变量,其中一个变量的值为零。在 try-catch 块中,我们创建了一个除以零的情况以引发 ArithmeticException。在 catch 块中,我们处理了 Exception,使用 getStackTrace() 方法从中检索了一个 StackTraceElement 数组,然后在数组的第一个元素上使用 getFileName() 方法,打印文件名。

Open Compiler
package com.tutorialspoint; public class StackTraceElementDemo { public static void main(String[] args) { // variables to store int values int a = 0, b = 1, c; try { // being divide by zero, this line will throw an ArithmeticException c = b / a; }catch(Exception e) { // get the array of StackTraceElement StackTraceElement[] stackTraceElements = e.getStackTrace(); // print the file name System.out.println(stackTraceElements[0].getFileName()); } } }

输出

让我们编译并运行上述程序,这将产生以下结果:

StackTraceElementDemo.java
java_lang_stacktraceelement.htm
广告