上面我們講了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。
文章引用 2dot5