问题
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