【发布时间】:2014-11-01 02:43:01
【问题描述】:
我目前正在为学校编写我的项目,其中需要我读写 txt 文件。我可以正确阅读它们,但我只能在最后从附加的 FileWriter 写入它们。我希望能够通过首先删除行上的数据然后写入新数据来覆盖行号上的 txt 文件中的内容。我尝试使用这种方法...
public void overWriteFile(String dataType, String newData) throws IOException
{
ReadFile file = new ReadFile(path);
RandomAccessFile ra = new RandomAccessFile(path, "rw");
int line = file.lineNumber(path, dataType);
ra.seek(line);
ra.writeUTF(dataType.toUpperCase() + ":" + newData);
}
但我相信 seek 方法以字节而不是行号移动。任何人都可以帮忙。在此先感谢:)
附: file.lineNumber 方法返回旧数据所在的确切行,因此我已经有了需要写入的行号。
编辑:找到解决方案!谢谢大家:)如果有人感兴趣,我会在下面发布解决方案
public void overWriteFile(String dataType, String newData, Team team, int dataOrder) throws IOException
{
try
{
ReadFile fileRead = new ReadFile(path);
String data = "";
if(path == "res/metadata.txt")
{
data = fileRead.getMetaData(dataType);
}
else if(path == "res/squads.txt")
{
data = fileRead.getSquadData(dataType, dataOrder);
}
else if(path == "res/users.txt")
{
data = fileRead.getUsernameData(dataType, dataOrder);
}
else if(path == ("res/playerdata/" + team.teamname + ".txt"))
{
//data = fileRead.getPlayerData(dataType, team.teamname, dataOrder);
}
BufferedReader file = new BufferedReader(new FileReader(path));
String line;
String input = "";
while((line = file.readLine()) != null)
{
input += line + '\n';
}
input = input.replace(dataType.toUpperCase() + ":" + data, dataType.toUpperCase() + ":" + newData);
FileOutputStream out = new FileOutputStream(path);
out.write(input.getBytes());
}
catch(Exception e)
{
System.out.println("Error overwriting file: " + path);
e.printStackTrace();
}
}
【问题讨论】:
-
如果不知道每行的长度,就不能随机访问给定的行。只需复制所有行,直到您要查找的那一行,然后写下它的替换,然后再写其余的行。
-
如果您找到了解决方案 - 与其在问题中发布,不如将其发布为您问题的答案。
标签: java file text file-io randomaccessfile