获取当前类的名称,并使用该名称创建一个txt [英] Get the name of the current class and create a txt with that name
本文介绍了获取当前类的名称,并使用该名称创建一个txt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
特别是我需要该程序来创建文本文件.文本文件的名称为类名称.
我试过了,但不起作用:
Especially I need the program to create a text file. The name of the text file to be the class name.
I tried this but does not work:
String className = this.getClass().getName();
File file = new File("C:\\" + className + ".txt");
推荐答案
尽管您正在创建File
对象,但是您并没有要求它在文件系统中创建它.
Although you are creating a File
object, you are not telling it to create it in the filesystem.
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
而不是getName
. getName
会为您提供完整的程序包和类名(com.package.ClassName
),而getSimpleName
只会为您提供类名(ClassName
)
I also think you might want to use getSimpleName
instead of getName
. getName
will get you the entire package and class name (com.package.ClassName
) whereas getSimpleName
will just get the class name (ClassName
)
这篇关于获取当前类的名称,并使用该名称创建一个txt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文