问题描述
我正在用Java编写一个带有文本文件的程序,我需要做的是修改文件中的特定字符串。 例如,文件有一行(该文件包含许多行),例如“ username,password,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对象,表示与此对象相同的字符序列时,结果为true。 -
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","@@@@");
}
}
如果要使用同一文件,请将内容存储在缓冲区(字符串数组或列表)中,然后将缓冲区的内容写入同一文件中。