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
}
}

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

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

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

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

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

我只需要用一个文件做很多类,或者也许有一个简单的类可以做所有事情(写、打开、读、关(,我是 Java 新手,我想也许在这里我可以得到帮助,谢谢

看看这个。 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();
}
}

最新更新