English 中文(简体)
如何修改文件的某些内容, 并使用 java 保存在同一文件中
原标题:how to modify some of the contents of the file and save in the same file using java
  • 时间:2012-05-22 11:55:01
  •  标签:
  • java

我有一个单词及其频率计数的文本文件。 当我给出任何单词时, 如果该单词与文本文件中的单词匹配, 那么我就需要加增它的频率计数 。 如何更改文本文件中的值? 如何在 Java 中进行此进程 。 请建议任何想法 。 提前感谢 。

myfile.txt

word    4
self    5
defence 3
argue   7

当我给“自我”这个词的时候, 然后在同一个“ Myfile. txt” 文本文档中, 它需要覆盖 :

word    4
self    6
defence 3
argue   7
最佳回答

在不直接回答您的问题的同时, 考虑使用 < code>java. lang. properies 来管理文件 :

  • each word is a unique value and can be used a property name (key)
  • the frequency count is the value to be associated with each word
  • Properties has load() and store() methods for reading from and writing to files
问题回答

您可以在文本文件中插入字符, 您只能替换 < em> 替换 < / em > 或 < em> 附加 < / em > 数据 。

换句话说,如果您从 9 10 , 您将不得不在 9 之后将所有字符向右移动一步, 以便给 10 留出空间 。

The best way, IMHO, is to use a thrid party API that takes care of all the reading and writing. My favourite for this is http://commons.apache.org/io/ Check out the class FileUtils. I think it contains all the methods you need.

您可以读/ 写到文件, 如果您使用足够空间来写增殖值, 可以填入一些空白, 例如 :

word    4___
self    11__
defence 3___
argue   7___

但你需要有一个上限才能提前知道

您可以使用二进制表达式, 用 4 字节存储 32 位字节, 但是这样您就会失去文件的人文可读性 。

解决你问题的典型办法是建立一个数据库,这个数据库是为这种工作而建立的,它可能看起来规模过大,但今天,有许多小型的模拟数据库。我上次使用数据库是几年前的Hsqldb。

使用 a

Map<String,Integer> words = new HashMap<String,Integer>();

to store all the words count. Then you can easily save all the keys to a file in the format you prefer





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签