2015-06-28 2 views
0

Программа, которую я пишу, требует, чтобы строка была введена в определенную строку текстового файла.Как вставить строку текста в середине текстового файла 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); 
    } 
+0

Сообщите, пожалуйста, свой код. –

+0

Возможный дубликат [Я хочу открыть текстовый файл и отредактировать определенную строку в java] (http://stackoverflow.com/questions/17218971/i-want-to-open-a-text-file-and-edit -a-specific-line-in-java) –

+0

@RamanShrivastava Моя программа должна сбрасывать строки в файле, а не редактировать одну строку. –

ответ

0

Если вы читаете содержимое файла в виде списка, вставив строку в середине «файла» это просто вопрос вызова List.insert(index, value) в соответствующем индексе.

+0

Энди, Большое спасибо за вашу помощь. Хотел бы я знать об этом методе. –

+0

Почему компилятор говорит «Невозможно найти переменные строки» с помощью этого 'lines.insert ((call + 1), ac8ud.toUpperCase());' –

+0

lines - это имя моего списка, который содержит точный контент текстового файла –

Смежные вопросы