获取当前类的名称并使用该名称创建一个txt

时间:2019-12-23 11:09:50

标签: java file reflection

特别是我需要该程序来创建文本文件。文本文件的名称为类名称。
我试过了,但是不起作用:

String className = this.getClass().getName();
File file = new File("C:\\" + className + ".txt");

1 个答案:

答案 0 :(得分:1)

尽管您正在创建一个File对象,但是您并没有要求它在文件系统中创建它。

String className = this.getClass().getSimpleName();

String fileName = String.format("%s.txt", className);

try {
    new File(fileName).createNewFile();
} catch (IOException e) {
    throw new RuntimeException(String.format("Error creating new file '%s'", fileName), e);
}

我还认为您可能希望使用getSimpleName而不是getNamegetName将为您提供完整的程序包和类名(com.package.ClassName),而getSimpleName只会为您提供类名(ClassName