文件内容
读文件
package wrtest;
import java.io.*;
public class ReadTest {
public static void main(String[] args) {
// 创建文件对象
File file = new File("read.txt");
try {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
try {
String result = bufferedReader.readLine();
// 循环读取文件内容
while (result != null) {
System.out.println(result);
result = bufferedReader.readLine();
}
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输出内容
写文件
覆盖原有内容
package wrtest;
import java.io.*;
public class WriteTest {
public static void main(String[] args) {
try {
FileWriter file = new FileWriter("read.txt");
BufferedWriter bufferedWriter = new BufferedWriter(file);
// 覆盖原有内容添加
bufferedWriter.write("oooooooo");
bufferedWriter.write("aaaaaaaaaaaa");
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
添加结果
追加内容
package wrtest;
import java.io.*;
public class WriteTest {
public static void main(String[] args) {
try {
// 第二个参数为 true 时,表示向文件中追加内容
FileWriter file = new FileWriter("read.txt",true);
BufferedWriter bufferedWriter = new BufferedWriter(file);
// 向文件中追加内容
bufferedWriter.write("\n");
bufferedWriter.write("iiiiiiiiii");
bufferedWriter.write("\n");
bufferedWriter.write("pppppppppp");
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
添加结果