Get the name of the current class and create a txt with that name [closed]

不羁岁月 提交于 2019-12-31 07:50:05

问题


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");

回答1:


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);
}

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)



来源:https://stackoverflow.com/questions/59454299/get-the-name-of-the-current-class-and-create-a-txt-with-that-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!