繁体   English   中英

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

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

我为项目创建的系统将是Java中的课程注册系统。

我现在面临的问题是如何追加到特定行(可以说是指学生证),以便注册代码模块位于逗号后。

每当我尝试追加时,它总是会追加到文件的最后一行。

文本文件的示例:
文字档范例

在注册模块之后,我还需要显示该特定科目的该特定学生行的所有模块。

我正在研究解决方案。 有人说实现arrayList-> File /从文件写入和读取数据会更容易。

谁能帮我解决这个问题?

首先读入您的文件。

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

然后找到并修改您的行,在本示例中,我将修改以“ 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);
    }
}

因此,现在toWrite具有您要写入文件的所有行。

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

您应该真正尝试使用基于JSON的方法,以减少笨拙并消除混乱。 这是一个工作示例。 我的代码每次都会添加一个新学生,并且每次都会向现有学生添加一个新模块。 该代码并未真正优化,因为这仅用于说明

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