特别是我需要该程序来创建文本文件。文本文件的名称为类名称。
我试过了,但是不起作用:
String className = this.getClass().getName();
File file = new File("C:\\" + className + ".txt");
答案 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
而不是getName
。 getName
将为您提供完整的程序包和类名(com.package.ClassName
),而getSimpleName
只会为您提供类名(ClassName
)