Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 创建一个txt文件,并将类名作为txt文件的名称_Java - Fatal编程技术网

Java 创建一个txt文件,并将类名作为txt文件的名称

Java 创建一个txt文件,并将类名作为txt文件的名称,java,Java,我正在编写一个程序,用类的名称创建一个文本文件。 我尝试了以下代码并说:不能从静态上下文引用非静态变量类名。我还尝试将static设置为className字符串,但它再次表示非静态变量这不能从静态上下文引用 String className = this.getClass().getName(); File file = new File("C:\\" + className + ".txt"); public static String logFileName = "C:\\"+class

我正在编写一个程序,用类的名称创建一个文本文件。 我尝试了以下代码并说:不能从静态上下文引用非静态变量类名。我还尝试将static设置为className字符串,但它再次表示非静态变量这不能从静态上下文引用

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

File file = new File("C:\\" + className + ".txt");

public static String logFileName = "C:\\"+className +".txt";

使用此选项获取类名


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

创建当前类的对象,然后使用它获取当前类名,然后使用
createNewFile()
在所需位置创建新文件。但请注意,位置应该存在

public class JavaCodes {

String getName() {
    return this.getClass().getName();
}
public static void main(String[] args) throws java.lang.Exception {
    JavaCodes obj = new JavaCodes();
    String className = obj.getName();
    File file = new File("C:\\Users\\MrGreen\\Desktop\\" + className + ".txt");
    file.createNewFile();
  }
}

这回答了你的问题吗?这是为了得到实际的名字,但仍然不能解决我的问题..tnx无论如何,感觉很好,谢谢你,但我需要在外部写main@04k这只是一个示例,尽管您可以在任何函数中编写相同的代码,但它将起作用。因为它不是静态的。