I feel like this is a bad practice to store a file inside a string. Is there an alternative way to do this, because I want to compare a list of keys and do an indexOf(key) on the file.开发者_JAVA技巧 The key could be anywhere in the file.
You could use a BufferedReader to pull in the data a chunk at a time:
BufferedReader reader = new BufferedReader(
new FileReader(file));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
...
and test each small string. You'd need to keep track of the index, but this would use much less memory.
A String
should be just fine as long as it fits in memory without problems.
An even better options is perhaps to do a pass over the file and store the keys in a HashSet
, or in a HashMap
mapping for instance the keywords to their offsets in the file.
If you're files are large, and you're only attempting to perform an indexOf operation, it might be best to load the file into memory in stages. Set an appropriate buffer on a BufferedReader and then read into the buffer. Perform your indexOf operation. If it fails, repeat this, but add the size of the number of characters your buffer reads to the return value of the indexOf function.
Depending on the reason why you are using the file in this way, it could be bad practice. But, generally, it's not.
If you are using the file as a glorified properties file, then maybe you should reformat the text in the file and read it in as a properties file.
If you could store the the keys and values in a database, then that would be a better solution than searching a string.
But if you have a text file that you are searching to find if it contains certain keywords, then you are already using the most simple solution.
精彩评论