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.");
}
}
}
下面是代码。我想用我创建的类来创建一个文件,写一些东西。然后,我使用main类检查该文件是否存在。
然而,我不知道为什么,但是主类不识别我(可能)创建的文件。谁能告诉我怎么把它们联系起来?
我知道这个程序可能有一些小错误。我稍后会解决这个问题。
谢谢。
您从未调用过构造函数。
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.");
}
}
}
您的问题:
- 没有创建类的实例
- 没有初始化
File file
,所以总是null 纯文本文件最好使用
utf-8
。试试这个:
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Fileverifynanoha {
private File file;
private Path path;
public Fileverifynanoha(String fp) {
this.path = Paths.get(fp);
this.file = path.toFile();
}
public void createFile()// this class wants to create a file, write something, and close it.
{
Charset charset = Charset.forName("UTF-8");
String s = "Takamachi Nanoha. Shirasaki Tsugumi.!";
BufferedWriter filewriter = null;
try {
filewriter = Files.newBufferedWriter(path, charset);
filewriter.write(s, 0, s.length() - 1);
filewriter.close();
} 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.
{
Fileverifynanoha f = new Fileverifynanoha("./txttest.txt");
f.createFile();
if (f.file.exists() && !f.file.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.");
}
}
}