JAVA:一起读写文件 [英] JAVA : read and write a file together

查看:116
本文介绍了JAVA:一起读写文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取一个Java文件,并同时修改它。这是我需要做的:我的文件格式为:

  aaa 
bbb
aaa
ccc
ddd
ddd

我需要通读文件并获得发生次数,并修改重复项以获得以下文件:

  aaa  -  2 
bbb - 1
ccc - 1
ddd - 2

RandomAccessFile 来做到这一点,但是做不到。有人可以帮我解决这个问题的代码吗?

解决方案

如果你不做两件事,同时。最好的方法是遍历整个文件,计算每个字符串中所有出现的哈希值,然后将所有结果写入另一个文件。那么如果你需要的话,把新文件移到旧文件上。



你不想同时读写同一个文件。您的文件偏移将在每次写入时发生移动,读取光标将不会跟踪该文件。


I am trying to read a java file and modify it simultaneously. This is what I need to do : My file is of the format :

aaa
bbb
aaa
ccc
ddd
ddd

I need to read through the file and get the count of the # of occurrences and modify the duplicates to get the following file:

aaa -  2
bbb -  1
ccc -  1
ddd -  2

I tried using the RandomAccessFile to do this, but couldn't do it. Can somebody help me out with the code for this one?

解决方案

It's far easier if you don't do two things at the same time. The best way is to run through the entire file, count all the occurrences of each string in a hash and then write out all the results into another file. Then if you need to, move the new file over the old one.

You never want to read and write to the same file at the same time. Your offsets within the file will shift everytime you make a write and the read cursor will not keep track of that.

这篇关于JAVA:一起读写文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆