[英]How can I append to a particular row using text file in JAVA?
首先读入您的文件。
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.