在Java文本文件中在特定位置将字符串附加到现有字符串的末尾

时间:2018-12-27 19:27:03

标签: bufferedreader filereader randomaccessfile

Exp- 在文本文件中,我们具有以下主题以及一些描述。


#重复注释

这是......的主要主题。

#Vector分析

它涵盖了顺序的所有方面。...

#Cloud Computing

为所有用户创建标头帐户


我们必须在特定行中向主题添加/添加新标签 对于exp-

#重复注释#Maven构建

#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 :(得分:0)

将输出写入文件GSTR_modified.txt。该代码以及示例输入文件也可用here。 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();
    }
}