如何使用 Java 替换文件中的特定行?
How to replace a specific line in a file using Java?
如何使用 FileWriter 和 PrintWriter 覆盖文本文件中的特定行?我不想每次都创建一个新文件。
编辑:我能否只循环浏览文件,获取指定行号处字符串的长度,然后在到达该行后使用该长度退格(删除字符串),然后写入新数据?
public static void setVariable(int lineNumber, String data) {
try {
// Creates FileWriter. Append is on.
FileWriter fw = new FileWriter("data.txt", true);
PrintWriter pw = new PrintWriter(fw);
//cycles through file until line designated to be rewritten is reached
for (int i = 1; i <= lineNumber; i++) {
//TODO: need to figure out how to change the append to false to overwrite data
if (i == lineNumber) {
pw.println(data);
pw.close();
} else {
// moves printwriter focus to next line (doesn't overwrite)
pw.println("");
}
}
}
}
如果您使用的是 Java 7 或更高版本并且 lineNumber
从 1 开始,您可以执行以下操作:
public static void setVariable(int lineNumber, String data) throws IOException {
Path path = Paths.get("data.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.set(lineNumber - 1, data);
Files.write(path, lines, StandardCharsets.UTF_8);
}
显然如果 lineNumber
从 0 开始,那么:
lines.set(lineNumber, data);
如何使用 FileWriter 和 PrintWriter 覆盖文本文件中的特定行?我不想每次都创建一个新文件。
编辑:我能否只循环浏览文件,获取指定行号处字符串的长度,然后在到达该行后使用该长度退格(删除字符串),然后写入新数据?
public static void setVariable(int lineNumber, String data) {
try {
// Creates FileWriter. Append is on.
FileWriter fw = new FileWriter("data.txt", true);
PrintWriter pw = new PrintWriter(fw);
//cycles through file until line designated to be rewritten is reached
for (int i = 1; i <= lineNumber; i++) {
//TODO: need to figure out how to change the append to false to overwrite data
if (i == lineNumber) {
pw.println(data);
pw.close();
} else {
// moves printwriter focus to next line (doesn't overwrite)
pw.println("");
}
}
}
}
如果您使用的是 Java 7 或更高版本并且 lineNumber
从 1 开始,您可以执行以下操作:
public static void setVariable(int lineNumber, String data) throws IOException {
Path path = Paths.get("data.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.set(lineNumber - 1, data);
Files.write(path, lines, StandardCharsets.UTF_8);
}
显然如果 lineNumber
从 0 开始,那么:
lines.set(lineNumber, data);