如何在文本文件中间插入一行文本 Java
How insert a line of text in the middle of a text file Java
我正在编写的程序要求在文本文件的特定行中输入一个字符串。
关键是必须保留所有行,所以如果文件看起来像:
AAA
BBB
CCC
DDD
FFF
它应该看起来像:
AAA
BBB
CCC
DDD
EEE
FFF
手术后。所有行都向下移动以容纳给定行上的新字符串。到目前为止,我正在尝试使用循环,但失败了。如有任何提示,我们将不胜感激。
代码:
// This method does the interfacing with the logfile. Probably don't run it solo.
// Before: We have a call stored in var ac8ud that needs to be appended to the text file on line 'count' + 1
// After: The call is inserted and all of the elements below the call are shifted down 1 slot
// There will be one more line in the text file than before this was run because of the additional call
public void writeCall() throws IOException{
{
File logpath = new File("log.txt");
List<String> lines = Files.readAllLines(logpath.toPath());
int count = (call * 10) + 1; // Count is the total amount of lines in the text file.
String copy2;
String copy; // Used to hold the next line of the text file in the for loop while it is overwritten
String copy1 = lines.get(count - 1); // Copies the last element of list to add on after the loop
for(int i = call + 1; i < count-1; i++) {
copy = lines.get(i); // Read the line that is about to be overwritten by the line above it moving down
copy2 = lines.get(i + 1);
lines.set(i+1, copy); // Move down a line
}
lines.add(copy1);
lines.set(call + 1, ac8ud.toUpperCase()); // Copy, insert, and overwrite logfile
Files.write(logpath.toPath(), lines);
}
如果您正在将文件内容读入列表,在 "file" 中间插入一行只需在适当的索引处调用 List.insert(index, value)
即可。
我正在编写的程序要求在文本文件的特定行中输入一个字符串。
关键是必须保留所有行,所以如果文件看起来像:
AAA
BBB
CCC
DDD
FFF
它应该看起来像:
AAA
BBB
CCC
DDD
EEE
FFF
手术后。所有行都向下移动以容纳给定行上的新字符串。到目前为止,我正在尝试使用循环,但失败了。如有任何提示,我们将不胜感激。
代码:
// This method does the interfacing with the logfile. Probably don't run it solo.
// Before: We have a call stored in var ac8ud that needs to be appended to the text file on line 'count' + 1
// After: The call is inserted and all of the elements below the call are shifted down 1 slot
// There will be one more line in the text file than before this was run because of the additional call
public void writeCall() throws IOException{
{
File logpath = new File("log.txt");
List<String> lines = Files.readAllLines(logpath.toPath());
int count = (call * 10) + 1; // Count is the total amount of lines in the text file.
String copy2;
String copy; // Used to hold the next line of the text file in the for loop while it is overwritten
String copy1 = lines.get(count - 1); // Copies the last element of list to add on after the loop
for(int i = call + 1; i < count-1; i++) {
copy = lines.get(i); // Read the line that is about to be overwritten by the line above it moving down
copy2 = lines.get(i + 1);
lines.set(i+1, copy); // Move down a line
}
lines.add(copy1);
lines.set(call + 1, ac8ud.toUpperCase()); // Copy, insert, and overwrite logfile
Files.write(logpath.toPath(), lines);
}
如果您正在将文件内容读入列表,在 "file" 中间插入一行只需在适当的索引处调用 List.insert(index, value)
即可。