Java读写文本文件操作

时间:2024-01-04 08:11:02
 package com.test;

 import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader; /**
* Java读写文本文件操作
*
* @author penghuaiyi
* @date 2011-07-25
*/
public class TextUtils { //读取文本文件
public static void readTxt(){
try {
File file = new File("c:/test.txt");
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(new FileInputStream(file));
BufferedReader br = new BufferedReader(read);
String lineTXT = null;
while ((lineTXT = br.readLine()) != null) {
System.out.println(lineTXT );
}
read.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} //写入文本文件
public static void writeTxt(){
try{
File file = new File("c:/aa.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("aaaaaaaaa");
bw.newLine();
bw.write("bbbbbbbbb");
bw.flush();
bw.close();
fw.close();
}catch(Exception e){
e.printStackTrace();
}
} public static void main(String[] args) {
readTxt();
writeTxt();
} }