I have a simple text dictionary file, which contains words, separated by ‘;’.My problem is to read all words and store them in map without loading all file to a string(dictionary file may be very huge).
Here is my code, where i am trying to print these words to a console :
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
public class Dictionary {
private static Dictionary instance;
private Map DictionaryMap;
private String delimiter;
private Dictionary() {
}
private Dictionary(String dictfile, String delimiter) throws FileNotFoundException, IOException
{
FileReader fr = new FileReader(dictfile);
int position = 0;
StringBuffer buffer = new StringBuffer();
while ((position = fr.read()) != -1) {
char symbol = (char) fr.read();
if(symbol != ';') {
buffer.append(symbol);
System.out.println("Char is : "+symbol+" ;");
} else {
System.out.println("String is "+buffer+" ;");
buffer.delete(0, buffer.length()-1);
}
}
}
public void loadFromFile(File dictfile, String delimiter) {
}
public String getDelimiter() {
return delimiter;
}
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
But when i am trying to run this code on sample dict.txt file, which contains :
test1;test2 ;
Some of the symbols between delimiter (char ‘;’) doesn’t displays :
Char is : e ;
Char is : t ;
String is et ;
Char is : e ;
Char is : t ;
Char is : ;
Char is : \uffff ;
My question why it doesn’t works properly and how to read chars from fileinputstream (in my case) without type casting?
You are calling
fr.read()twice e.g.Therefore you are skipping input.
This should be:
Also it’s not generally a good idea to read the file 1 character at a time – you should try and use a
char []as a buffer and use theread(char[] cbuf, int off, int len)method, or for simplicity, use aBufferedReader.