如何使用 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
广告