java創建TXT文件並進行讀、寫、修改操作
這周忙的連滾帶爬的,終於在週末前把項目完工了。這次主要做的是一個UDP協議的轉發器,是一個純java寫的程序,沒有任何的框架在裏面。其中爲了保留住傳進來的數據,我們用TXT文本記錄下這些數據。文件代碼傳上來,需要的朋友直接下載就可以用。
import java.io.*;
/**
*
* 功能描述:創建TXT文件並進行讀、寫、修改操作
*
* @author <a href="mailto:[email protected]">KenZhang</a>
* @version 1.0
* Creation date: 2007-12-18 - 下午06:48:45
*/
public class ReadWriteFile {
public static BufferedReader bufread;
//指定文件路徑和名稱
private static String path = "D:/suncity.txt";
private static File filename = new File(path);
private static String readStr ="";
/**
* 創建文本文件.
* @throws IOException
*
*/
public static void creatTxtFile() throws IOException{
if (!filename.exists()) {
filename.createNewFile();
System.err.println(filename + "已創建!");
}
}
/**
* 讀取文本文件.
*
*/
public static String readTxtFile(){
String read;
FileReader fileread;
try {
fileread = new FileReader(filename);
bufread = new BufferedReader(fileread);
try {
while ((read = bufread.readLine()) != null) {
readStr = readStr + read+ "\r\n";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("文件內容是:"+ "\r\n" + readStr);
return readStr;
}
/**
* 寫文件.
*
*/
public static void writeTxtFile(String newStr) throws IOException{
//先讀取原有文件內容,然後進行寫入操作
String filein = newStr + "\r\n" + readStr + "\r\n";
RandomAccessFile mm = null;
try {
mm = new RandomAccessFile(filename, "rw");
mm.writeBytes(filein);
} catch (IOException e1) {
// TODO 自動生成 catch 塊
e1.printStackTrace();
} finally {
if (mm != null) {
try {
mm.close();
} catch (IOException e2) {
// TODO 自動生成 catch 塊
e2.printStackTrace();
}
}
}
}
/**
* 將文件中指定內容的第一行替換爲其它內容.
*
* @param oldStr
* 查找內容
* @param replaceStr
* 替換內容
*/
public static void replaceTxtByStr(String oldStr,String replaceStr) {
String temp = "";
try {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
// 保存該行前面的內容
for (int j = 1; (temp = br.readLine()) != null
&& !temp.equals(oldStr); j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
}
// 將內容插入
buf = buf.append(replaceStr);
// 保存該行後面的內容
while ((temp = br.readLine()) != null) {
buf = buf.append(System.getProperty("line.separator"));
buf = buf.append(temp);
}
br.close();
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* main方法測試
* @param s
* @throws IOException
*/
public static void main(String[] s) throws IOException {
ReadWriteFile.creatTxtFile();
ReadWriteFile.readTxtFile();
ReadWriteFile.writeTxtFile("20080808:12:13");
// ReadWriteFile.replaceTxtByStr("ken", "zhang");
}
}