如何在自己的文本文件中制作文本文件 class

How do I make a text file in its own class

我下面的代码展示了如何在 main.c 中创建一个文本文件。但是,当我把它放在它自己的 class 中时,它不起作用。我怎样才能把这段代码从我的主程序中取出并放在一个单独的 class?

try {
    File file = new File("data.txt");
    if (!file.exists()) {
        file.createNewFile();
    }
    PrintWriter pw = new PrintWriter(file);
    pw.println("this is my file content");
    pw.close();
    System.out.println("hi");
} catch (IOException ex) {
    Logger.getLogger(RST.class.getName()).log(Level.SEVERE, null, ex);
}

这行得通,但都是主要的。我想把它拿出来放在自己的class.

没有解释您想要 class 的哪些功能,但这应该是一个好的开始:

public class MySuperDuperTextClass {
   private File file = null;
   private String content = null;
   public File getFile() { return file; }
   public void setFile( File file ) { this.file = file; }
   public String getContent() { return content; }
   public void setContent( String content ) { this.content = content; }

public MySuperDuperTextClass( String filename ){
  try {
    File file = new File ( filename );
    if (!file.exists()){ 
        file.createNewFile(); 
    }
      PrintWriter pw = new PrintWriter(file);
      pw.println("this is my file content");
      pw.close();
      System.out.println("hi");
    } catch (IOException ex) {
        Logger.getLogger(RST.class.getName()).log(Level.SEVERE, null, ex);
    }
   // somewhere you may want to store the content of the file into
   // the this.content file:
   this.content = new 
       String(java.nio.file.Files.readAllBytes(Paths.get(filename))); 
}

我直接编码答案,所以你应该处理任何编译器错误。