[英]How to replace specific String in a text file by java?
我正在用java编写一个带有文本文件的程序,我需要做的是修改文件中的特定字符串。 例如,该文件有一行(该文件包含多行),如“用户名,密码,e,d,b,c,a”,我想将其修改为“用户名,密码,f,e,d,b ,c”我搜索了很多,但一无所获。 怎么处理?
一般来说,您可以通过 3 个步骤来完成:
你可以在 Stackoverflow 上搜索每一步的指令。
这是直接在 Stream 上工作的可能解决方案:
public static void main(String[] args) throws IOException {
String inputFile = "C:\\Users\\geheim\\Desktop\\lines.txt";
String outputFile = "C:\\Users\\geheim\\Desktop\\lines_new.txt";
try (Stream<String> stream = Files.lines(Paths.get(inputFile));
FileOutputStream fop = new FileOutputStream(new File(outputFile))) {
stream.map(line -> line += " manipulate line as required\n").forEach(line -> {
try {
fop.write(line.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
算法如下:
打开一个临时文件以保存编辑后的副本。
逐行读取输入文件。
检查当前行是否需要替换
可以使用String
类的各种方法来做到这一点:
equals
:将此字符串与指定的对象进行比较。 当且仅当参数不为 null 并且是表示与此对象相同的字符序列的 String 对象时,结果才为真。equalsIgnoreCase
:将此字符串与另一个字符串进行比较,忽略大小写考虑。contains
:当且仅当此字符串包含指定的 char 值序列时才返回 true。matches (String regex)
:判断此字符串是否与给定的正则表达式匹配。startsWith
:测试此字符串是否以指定的前缀开头(区分大小写)。endsWith
:测试此字符串是否以指定的前缀开头(区分大小写)。 还有其他谓词函数: contentEquals
, regionMatches
如果所需条件为true
,则为 currentLine 提供替换:
if (conditionMet) {
currentLine = "Your replacement";
}
或者使用String
方法replace/replaceFirst/replaceAll
一次性替换内容。
如果您的文件与此类似:
username:username123,
password:password123,
将文件加载到 String 后,您可以执行以下操作:
int startPosition = file.indexOf("username") + 8; //+8 is length of username with colon
String username;
for(int i=startPosition; i<file.length(); i++) {
if(file.charAt(i) != ',') {
username += Character.toString(file.charAt(i));
} else {
break;
}
System.out.println(username); //should prong username
}
编辑完所有要编辑的内容后,将编辑后的字符串保存到文件中。
有很多方法可以解决这个问题。 阅读 String 文档以了解对 String 的操作。 没有您的代码,我们无法为您提供足够的帮助。
您可以这样尝试:首先,逐行读取文件并检查每一行是否存在要替换的字符串,将其替换,并将内容写入另一个文件中。 这样做直到达到EOF。
import java.io.*;
public class Files {
void replace(String stringToReplace, String replaceWith) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("/home/asn/Desktop/All.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("/home/asn/Desktop/All-copy.txt"));
String line;
while((line=in.readLine())!=null) {
if (line.contains(stringToReplace))
line = line.replace(stringToReplace, replaceWith);
out.write(line);
out.newLine();
}
in.close();
out.close();
}
public static void main(String[] args) throws IOException {
Files f = new Files();
f.replace("amount", "@@@@");
}
}
如果要使用相同的文件,则将内容存储在缓冲区(字符串数组或列表)中,然后将缓冲区的内容写入同一个文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.