上面我们讲了Hello World!,我们完成了一个程序,得到的结果该如何保存,总不能每次开机都要运行一次吧?所以我们需要一个载体把我们的结果记录下来。下面我就介绍一个方便的记录方式,文件读写。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
public class TestFile {
public TestFile(){
}
public void appendWriterFile(String fileName,String content){
try {
FileWriter writer = new FileWriter(fileName,true);
writer.write(content);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writerFile(String fileName,String content){
try {
FileWriter writer = new FileWriter(fileName);
writer.write(content);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String readFile(String fileName){
StringBuffer results = new StringBuffer();
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
results.append(tempString+"\r\n");
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return results.toString();
}
public void randomWriterFile(String fileName,String content){
try {
RandomAccessFile writer = new RandomAccessFile(fileName, "rw");
long length = writer.length();
writer.seek(length);
writer.writeBytes(content);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String randomReadFile(String fileName){
StringBuffer results = new StringBuffer();
RandomAccessFile reader = null;
try {
reader = new RandomAccessFile(fileName, "r");
long length = reader.length();
// 读文件的起始位置
int index = (length > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
reader.seek(index);
String tempString = null;
while ((tempString = reader.readLine()) != null) {
results.append(tempString+"\r\n");
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return results.toString();
}
public static void main(String[] args) {
String fileName="/Users/victor/test.txt";
String content="Hello World!\r\n"; // 加入换行符 \r\n
TestFile test =new TestFile();
//写入文件
test.writerFile(fileName, content);
test.appendWriterFile(fileName, content); //追加写入
//读取文件
String results = test.readFile(fileName);
System.out.println(results);
}
}
快速的学会文件的读写,这些能满足大家大部分需求,如果要对流操作请查api。