[英]Java how to create, open, write, and read then close the file
so here's the problem, i stack on how to create, open, write, and read file, with this code 所以这是问题所在,我在此堆栈上介绍了如何使用此代码创建,打开,写入和读取文件
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
}
}
so the problem is when i tried to write something in the file, i using class Formatter and it always format all the text data that in it before and class Formatter won't work if public int check_file()
is equals to 1 because it skip from creating file using Formatter class and can't just write in the file because variable x undefined 所以问题是当我尝试在文件中写一些东西时,我使用了Formatter类,并且它总是格式化之前的所有文本数据,如果
public int check_file()
等于1,则Formatter类将无法工作,因为它会跳过使用Formatter类创建文件,并且不能只写文件,因为变量x未定义
this is the code how i write text in a file 这是我如何在文件中写入文本的代码
public void recording_to_file(){
x.format(format, args);
}
and to closing file i need to handle error like this 并关闭文件,我需要处理这样的错误
public void close_file(){
try{
x.close();
}catch(Exception e){
file.close();
}
}
}
there was just ton of class that i need to do something with just one file, or maybe there was one simple class that can do all in one like(write, open, read, close), i am new in java, i think maybe in here i can get help, thank you 我只需要一个文件就可以做很多事情,或者也许有一个简单的类可以一并完成所有工作(写,打开,读,关闭),我是java的新手,我想在这里我可以得到帮助,谢谢
Take a look at this. 看看这个。 The second argument to the FileWriter costructor (true) tells it to only append data, instead of overwriting any.
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.