Java删除txt中文件中某一行数据
txt文件的格式如下
RefereeView1/192.168.0.102
RefereeView2/192.168.0.104
ArtScore1/192.168.0.107
ArtScore2/192.168.0.114
ArtScore3/192.168.0.112
CompletionScore2/192.168.0.108
CompletionScore1/192.168.0.101
ArtScore4/192.168.0.100
DiffcultyScore1/192.168.0.109
RefereeEdit/192.168.0.105
RefereeView3/192.168.0.106
比如要删除:CompletionScore1/192.168.0.101,请问如何实现?
坐等楼下高见
[解决办法]
LZ可以参考这里
要想直接删除还真没有什么好办法,都要去遍历,小数据效率还行,如果是大数据量效率就低了
[解决办法]
如果要删除任意数据的话,一般都要经过先检索、后处理的过程。
如何提高检索速度是关键。
其中可以为文件中的每行数据建立索引,如何建立索引,就要参考索引的使用方法了。
[解决办法]
可以将文件中的每行数据提取出来,放到指定的存储结构中,如链表、数组、Map等。
使用Java中支持这些结构的API来处理每行数据,处理完毕后,
再讲存储结构中的内容写回文件中。
[解决办法]
每行读取,然后再写入,如果包含CompletionScore2就不写入。
[解决办法]
不要真正的删除,因为删除没有什么好的方法,必须把整个文件再复制一次。
使用标记:例如把这一行的前多少个字节数据修改成标记的值,读取每一行时判断是否有删除的标记。
很多工具都这样做,当到例如半夜后启动一个线程把文件中被标记为删除的部分真正的删除。
[解决办法]
应该先把文件中的内容读取出来,然后循环查找需要删除的内容,接着还放回文件?我现在只想到这个办法。
[解决办法]
可以先考虑把要删除的行的内容用正则或者什么的写好,然后readline来遍历,符合的就不写入了,不符合才写入,等同于删除了
[解决办法]
public class JavaSeTest {
public static void main(String[] args) {
JavaSeTest test = new JavaSeTest();
List<String> list;
try {
list = test.readFile("E:\\test.txt","CompletionScore1/192.168.0.101");
test.writeFile("E:\\test.txt", list);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private List<String> readFile(String filePath, String str)throws IOException {
File file = new File(filePath);
BufferedReader reader = null;
List<String> list = new ArrayList<String>();
reader = new BufferedReader(new FileReader(file));
String text = reader.readLine();
while (text != null) {
if (!text.trim().equals(str)) {
list.add(text + "\r\n");
}
text = reader.readLine();
}
reader.close();
return list;
}
private void writeFile(String filePath, List<String> list)
throws IOException {
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(file);
for (String s : list) {
outputStream.write(s.getBytes());
}
outputStream.close();
}
}