Java如何创建,打开,写入和读取然后关闭文件

时间:2017-08-15 12:37:01

标签: java text-files

所以这就是问题, 我使用此代码

堆叠如何创建,打开,写入和读取文件
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类创建文件而不能只写入文件,因为变量x undefined

这是我在文件中写文本的代码

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

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

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

}

我只需要用一个文件来做一些类,或者可能有一个简单的类可以做一切就像(写,打开,读取,关闭),我是java的新手,我想也许在这里我可以得到帮助,谢谢

1 个答案:

答案 0 :(得分:0)

看看这个。 FileWriter costructor的第二个参数(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();
    }
}