Добавить строку в конец существующей строки с определенной позицией в текстовом файле на Java - PullRequest
0 голосов
/ 27 декабря 2018

Exp - В текстовом файле у нас есть следующие темы с некоторым описанием.


# Повторите аннотацию

Это основная тема для .....

# Векторный анализ

Он охватывает все аспекты последовательных ....

# Облачные вычисления

Создание учетных записей для всех пользователей


Мы должны добавить / добавить новые теги к темам в определенной строке. Для exp-

# Повторить аннотацию #Maven build

#Cloud Computing # SecondYear

Файл f = новый файл ("/ user / imp / value / GSTR.txt");

    FileReader fr = new FileReader(f);
    Object fr1;
    while((fr1 = fr.read()) != null) {

        if(fr1.equals("#Repeat the annotation")) {
            FileWriter fw = new FileWriter(f,true);
        fw.write("#Maven build");
        fw.close();


        }
    }

****** #Maven добавляется в последнюю строку текстового файла, но не в определенную позицию рядом с темой

1 Ответ

0 голосов
/ 27 декабря 2018

Вывод записывается в файл GSTR_modified.txt.Код вместе с примером входного файла также доступен здесь .Код в репозитории github читает файл «input.txt» и записывает в файл «output.txt».

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) throws IOException {
    // Create a list to store the file content.
    ArrayList<String> list = new ArrayList<>();
    // Store the file content in the list. Each line becomes an element in the list.
    try (BufferedReader br = new BufferedReader(new FileReader("/user/imp/value/GSTR.txt""))) {
        String line;
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
    }
    // Iterate the list of lines.
    for (int i = 0; i < list.size(); i++) {
        // line is the element at the index i.
        String line = list.get(i);
        // Check if a line is equal to "#Repeat the annotation"
        if (line.contains("#Repeat the annotation")){
            // Set the list element at index i to the line itself concatenated with
            // the string " #Maven build".
            list.set(i,line.concat(" #Maven build"));
        }
        // Same pattern as above.
        if (line.contains("#Cloud Computing")){
            list.set(i,line.concat(" #SecondYear"));
        }
    }
    // Write the contents of the list to a file.
    FileWriter writer = new FileWriter("GSTR_modified.txt");
    for(String str: list) {
        // Append newline character \n to each element
        // and write it to file.
        writer.write(str+"\n");
    }
    writer.close();
    }
}
...