如何使用 Java 覆蓋 .txt 檔案中的一行?
使用的 API
String 類的 replaceAll() 方法接受兩個字串,分別表示正則表示式和替換字串,並用給定的字串替換匹配的值。
java.util 類(建構函式)接受 File、InputStream、Path 和 String 物件,使用正則表示式逐個標記讀取所有基本資料型別和字串(來自給定的源)。使用提供的 nextXXX() 方法從源讀取各種資料型別。
StringBuffer 類是 String 的可變替代方案,例項化此類後,可以使用 append() 方法向其中新增資料。
步驟
要覆蓋檔案的特定行 -
將檔案內容讀取到 String 中 -
例項化 File 類。
例項化 Scanner 類,並將檔案作為引數傳遞給其建構函式。
建立一個空的 StringBuffer 物件。
使用 append() 方法逐行將檔案內容新增到 StringBuffer 物件中。
使用 toString() 方法將 StringBuffer 轉換為 String。
關閉 Scanner 物件。
對獲得的字串呼叫 replaceAll() 方法,並將要替換的行(舊行)和替換行(新行)作為引數傳遞。
重寫檔案內容 -
例項化 FileWriter 類。
使用 append() 方法將 replaceAll() 方法的結果新增到 FileWriter 物件中。
使用 flush() 方法將新增的資料推送到檔案。
示例
import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class OverwriteLine { public static void main(String args[]) throws IOException { //Instantiating the File class String filePath = "D://input.txt"; //Instantiating the Scanner class to read the file Scanner sc = new Scanner(new File(filePath)); //instantiating the StringBuffer class StringBuffer buffer = new StringBuffer(); //Reading lines of the file and appending them to StringBuffer while (sc.hasNextLine()) { buffer.append(sc.nextLine()+System.lineSeparator()); } String fileContents = buffer.toString(); System.out.println("Contents of the file: "+fileContents); //closing the Scanner object sc.close(); String oldLine = "No preconditions and no impediments. Simply Easy Learning!"; String newLine = "Enjoy the free content"; //Replacing the old line with new line fileContents = fileContents.replaceAll(oldLine, newLine); //instantiating the FileWriter class FileWriter writer = new FileWriter(filePath); System.out.println(""); System.out.println("new data: "+fileContents); writer.append(fileContents); writer.flush(); } }
輸出
Contents of the file: Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills. Our content and resources are freely available and we prefer to keep it that way to encourage our readers acquire as many skills as they would like to. We don’t force our readers to sign up with us or submit their details either. No preconditions and no impediments. Simply Easy Learning! new data: Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills. Our content and resources are freely available and we prefer to keep it that way to encourage our readers acquire as many skills as they would like to. We don’t force our readers to sign up with us or submit their details either. Enjoy the free content
廣告