這個代碼撰寫的思路是什么啊
public void 替換(String filePath,String oldstr,String newStr) {
File f= new File(資料庫.路徑.住戶檔案路徑);
Long fileLength = f.length();
byte[] fileContext = new byte[fileLength.intValue()];
FileInputStream in = null;
PrintWriter out = null;
try {
in = new FileInputStream(filePath);
in.read(fileContext);
String str = new String(fileContext,"GBK");
str = str.replace(oldstr,newStr);
out = new PrintWriter(filePath);
out.write(str);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
out.flush();
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
uj5u.com熱心網友回復:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author :jiaolian
* @date :Created in 2021-01-15 21:42
* @description:檔案讀寫測驗
* @modified By:
* 公眾號:叫練
*/
public class FileTest {
public static void main(String[] args) {
replece("E:\\a1.txt","的","叫練");
}
//將檔案的字串替換
public static void replece(String filePath,String oldstr,String newStr) {
File f= new File(filePath);
Long fileLength = f.length();
byte[] fileContext = new byte[fileLength.intValue()];
FileInputStream in = null;
PrintWriter out = null;
try {
//將檔案讀進位元組陣列
in = new FileInputStream(filePath);
in.read(fileContext);
//位元組陣列轉化為字串
String str = new String(fileContext,"UTF-8");
str = str.replace(oldstr,newStr);
//替換的字串再寫入檔案
out = new PrintWriter(filePath);
out.write(str);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
out.flush();
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
方法的本意是將檔案的字串做替換,上面代碼有幾處錯誤的地方,已經寫明了簡單注釋,希望對你有幫助
uj5u.com熱心網友回復:
代碼還是寫的不夠健壯,比如當檔案過大,替換起來就會特別慢了。轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/249237.html
標籤:Java相關
下一篇:孫類繼承出問題
