简体   繁体   中英

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.

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.

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".

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.

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. 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();
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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