2017-08-15 46 views
0

所以这里的问题, 我堆了如何创建,打开,写入和读取文件,与此代码的Java如何创建,打开,写入和读取,然后关闭该文件

import java.util.*; 
import java.io.*; 

class class_Name{ 

Formatter x;      // Variable: creating new file 
File file = new File("file.txt"); // Variable: check file existence 

    //creating txt file 
    public void creating_file(){ 
     try{ 
      x = new Formatter("file.txt"); 
     }catch(Exception e){ 
      System.out.println("you got an error"); 
     } 
    } 

    public int check_file(){ 
     if(file.exists()){ 
      return 1; // in main method, check if file already exists just pass from creating file 
     }else{ 
      return 0; // in main method if return value 0, then it create new file with "public void creating_file()" method 
     } 
    } 

所以问题是当我试图在文件中写入某些东西时,我使用类Formatter,并且它始终格式化之前的所有文本数据,并且如果public int check_file()等于1,则类Formatter将不起作用,因为它使用Formatter从创建文件跳过类,不能在文件中只写了,因为变量x未定义

这是我的代码怎么写文本文件中的

public void recording_to_file(){ 
     x.format(format, args); 
    } 

,并关闭文件,我需要处理错误这样

public void close_file(){ 
     try{ 
      x.close(); 
     }catch(Exception e){ 
      file.close(); 
     } 
    } 

} 

只是有万吨级的,我需要做的事情只有一个文件,也可能有一个简单的类,可以做一个像(写,打开,阅读,关闭),我在新的java,我觉得也许在这里我能得到帮助,谢谢

+0

很难理解,你的故事有完全无关 –

+0

看看类'FileReader'和'FileWriter'(恕我直言)采取编码。 [reader](https://docs.oracle.com/javase/8/docs/api/index.html?java/io/FileReader.html)和[writer](http://docs.oracle.com/javase /8/docs/api/java/io/FileWriter.html)。您不需要将布尔转换为0或1 btw。按原样使用它。 – Matt

回答

0

看看这个。 FileWriter构造函数的第二个参数(true)告诉它只添加数据,而不是覆盖任何数据。

import java.util.*; 
import java.io.*; 

class SomeClass{ 

    Formatter x;      
    File file = new File("file.txt"); 

    public void creating_file(){ 
     try{ 
      x = new Formatter(new FileWriter(file, true)); 
     }catch(Exception e){ 
      System.out.println("you got an error"); 
     } 
    } 

    public boolean check_file(){ 
     return file.exists(); 
    } 
} 
相关问题