如何在文本文件Java中间插入一行文本

时间:2015-06-28 19:15:18

标签: java string loops text insert

我正在编写的程序需要在文本文件的特定行上输入字符串。

关键是必须保留所有行,所以如果文件看起来像:

AAA
BBB
CCC
DDD
FFF

应该看起来像:

AAA
BBB
CCC
DDD
EEE
FFF 

手术后。所有行都向下移动以容纳给定行上的新String。到目前为止,我正在尝试使用循环,但失败了。任何提示将不胜感激。

代码:

// 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); 
    }

1 个答案:

答案 0 :(得分:0)

如果您正在将文件的内容读入列表,请在&#34;文件的中间插入一行&#34;只需在适当的索引处调用 class B { B() { System.out.print("Inside Constructor B"); } A o=new A(); } 即可。