简体   繁体   English

如何在JAVA中使用文本文件附加到特定行?

[英]How can I append to a particular row using text file in JAVA?

The system I'm creating for my project would be a Course Registration System in Java. 我为项目创建的系统将是Java中的课程注册系统。

The problem I'm facing right now is how can I append to a particular row (we can say refer to the student ID) so that the registration code modules would be behind the line after the comma. 我现在面临的问题是如何追加到特定行(可以说是指学生证),以便注册代码模块位于逗号后。

Every time when I tried to append, it would always append to the last line of the file. 每当我尝试追加时,它总是会追加到文件的最后一行。

An example of the text file: 文本文件的示例:
文字档范例

After the registration of modules, I would also need to display all modules of that particular student row for that specific subject. 在注册模块之后,我还需要显示该特定科目的该特定学生行的所有模块。

I'm been researching about the solution to come off. 我正在研究解决方案。 Some say it would be easier to implement the arrayList->File / writing and reading data from the file. 有人说实现arrayList-> File /从文件写入和读取数据会更容易。

Could anyone help me solve this problem? 谁能帮我解决这个问题?

First read in your file. 首先读入您的文件。

List<String> lines = Files.readAllLines(Paths.get("/path/to/your/file.txt"), StandardCharsets.UTF_8);

Then find and modify your line, in this example I modify the line that starts with "0327159". 然后找到并修改您的行,在本示例中,我将修改以“ 0327159”开头的行。

List<String> toWrite = new ArrayList<>();

for(int i = 0; i<lines.size(); i++){
    String line = lines.get(i);
    if(line.startsWith("0327159")){
        String updated = line.trim() + ", more text\n";
        toWrite.add(updated);
    } else{
        toWrite.add(line);
    }
}

So now toWrite has all of the lines that you want to write to your file. 因此,现在toWrite具有您要写入文件的所有行。

Files.write(
    Paths.get("/path/to/outfile.txt"), 
    toWrite, 
    StandardCharsets.UTF_8, 
    StandardOpenOptions.CREATE, 
    StandardOpenOptions.TRUNCATE_EXISTING );

You should really try a JSON based approach, to make it less clumsy and eliminate confusion. 您应该真正尝试使用基于JSON的方法,以减少笨拙并消除混乱。 Here's a working example. 这是一个工作示例。 My code adds a new student every time and adds a new module to existing students every time. 我的代码每次都会添加一个新学生,并且每次都会向现有学生添加一个新模块。 The code is not really optimized since this is just for illustration 该代码并未真正优化,因为这仅用于说明

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ModuleRegistration
{
    public static void main(String[] args) throws IOException
    {
        File file = new File("C:\\MyStudents.txt");
        if (!file.exists())
            file.createNewFile();

        List<String> lines = Files.readAllLines(Paths.get(file.getAbsolutePath()));
        ObjectMapper mapper = new ObjectMapper();
        List<StudentInfo> newLines = new ArrayList<StudentInfo>(2);
        for (String line : lines)
        {
            StudentInfo info = mapper.readValue(line, StudentInfo.class);
            String modules = info.getModules() == null ? "" : info.getModules();
            if (!"".equals(modules))
                modules += ",";
            modules += "Module" + System.currentTimeMillis();
            info.setModules(modules);
            newLines.add(info);
        }
        StudentInfo info = new StudentInfo();
        long time = System.currentTimeMillis();
        info.setId(time);
        info.setModules("Module" + time);
        info.setName("Name" + time);
        info.setPassword("Password" + time);
        info.setType("Local");
        newLines.add(info);

        try (FileWriter writer = new FileWriter(file, false);)
        {
            for (StudentInfo i : newLines)
            {
                writer.write(i.toString());
                writer.write(System.lineSeparator());
            }
        }

        System.out.println("Done");
    }

    static class StudentInfo
    {
        @JsonProperty("id")
        private long id;

        @JsonProperty("password")
        private String password;

        @JsonProperty("name")
        private String name;

        @JsonProperty("type")
        private String type;

        @JsonProperty("modules")
        private String modules;

        // getters and setters

        @Override
        public String toString()
        {
            try
            {
                return new ObjectMapper().writeValueAsString(this);
            }
            catch (JsonProcessingException exc)
            {
                exc.printStackTrace();
                return exc.getMessage();
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM