如何使用Java覆盖.txt文件中的行?
API的使用
String类的replaceAll()方法接受两个表示正则表达式的字符串和一个替换String,并将匹配的值替换为给定的String。
的java.util类(构造)接受文件,InputStream的,路径和,字符串对象,读取所有通过令牌使用正则表达式令牌的原始数据类型和字符串(从给定的来源)。使用nextXXX()
提供的方法从源中读取各种数据类型。
该StringBuffer的类是可变的替代字符串,这个实例类,你可以使用添加数据后append()
的方法。
程序
覆盖文件的特定行-
将文件的内容读取为String-
实例化File类。
实例化Scanner类,将文件作为参数传递给其构造函数。
创建一个空的StringBuffer对象。
使用append()
方法将文件内容逐行添加到StringBuffer对象。
使用toString()
方法将StringBuffer转换为String。
关闭扫描仪对象。
在获得的字符串上调用replaceAll()方法,将要替换的行(旧行)和替换行(新行)作为参数。
重写文件内容-
实例化FileWriter类。
replaceAll()
使用append()
方法将方法的结果添加到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 { //实例化File类 String filePath = "D://input.txt"; //实例化Scanner类以读取文件 Scanner sc = new Scanner(new File(filePath)); //实例化StringBuffer类 StringBuffer buffer = new StringBuffer(); //读取文件的行并将其附加到StringBuffer- while (sc.hasNextLine()) { buffer.append(sc.nextLine()+System.lineSeparator()); } String fileContents = buffer.toString(); System.out.println("Contents of the file: "+fileContents); //关闭扫描仪对象 sc.close(); String oldLine = "No preconditions and no impediments. Simply Easy Learning!"; String newLine = "Enjoy the free content"; //用新行替换旧行 fileContents = fileContents.replaceAll(oldLine, newLine); //实例化FileWriter类 FileWriter writer = new FileWriter(filePath); System.out.println(""); System.out.println("new data: "+fileContents); writer.append(fileContents); writer.flush(); } }
输出结果
Contents of the file: nhooo.com 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: nhooo.com 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