java - 我想创建一个类来创建文件,并使用主类来检查该文件是否已创建,但我的代码失败。 ( java )

标签 java file

public class Fileverifynanoha 
{
    private File fileext;
    private Path filepath;
    public Fileverifynanoha()//this class wants to create a file, write something, and close it.
{
    filepath = Paths.get("./txttest.txt");
    Charset charset = Charset.forName("US-ASCII");
    String s = "Takamachi Nanoha. Shirasaki Tsugumi.!";
    try (BufferedWriter filewriter = Files.newBufferedWriter(filepath,charset))
    {
        filewriter.write(s,0,s.length()-1);   
    }
    catch(IOException e)
         {
            System.err.println(e);
         }

}//end of this class
/**
 * @param args the command line arguments
 */
public static void main(String[] args)//the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{

    if (filetxt.exists()&&!filetxt.isDirectory())//object does not create any real thing, therefore nothing true will return.
    {
        System.out.println("File exist.");
    }
    else
    {
        System.out.println("File does not exist.");
    }
}
}

这是代码。我想用我创建的类来创建一个文件,写一些东西。然后,我使用主类来检查该文件是否存在。

但是,我不知道为什么,但主类无法识别我(可能)创建的文件。谁能告诉我如何将它们链接在一起?

我知道这个程序中可能存在一些小错误。我稍后会解决这个问题。

谢谢。

最佳答案

你从未调用过你的构造函数。

public static void main(String[] args)//the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
    Fileverifynanoha fvn = new Fileverifynanoha();
    if (fvn.filetxt.exists()&&!fvn.filetxt.isDirectory())
    {
        System.out.println("File exist.");
    }
    else
    {
        System.out.println("File does not exist.");
    }
}
}

关于java - 我想创建一个类来创建文件,并使用主类来检查该文件是否已创建,但我的代码失败。 ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30430781/

相关文章:

java - 如何将 JSON 文件反序列化为具有嵌套类的 ArrayList?

java - 如何删除 fragment 中的 ListView 项?

java - 什么是 Swift 中的 Java HashMap<String,Integer> 的等价物

java - 为什么 StringBuilder 会抛出 NullPointerException

file -\x00 在二进制文件中是什么意思?

c++ - 在文本文件中搜索短语 C++

file - 为Hadoop作业指定多个输入文件

Java:套接字还是 RMI?

c# - 锁定文件不被除我以外的任何人更改?

c - 从 C 上的终端输入 "cat"读取文件