I’m trying to have my application read through a text file and look for a string. If the string does not exist, it makes it using println. The only problem I’m having is that it doesn’t seem to read the text file. What I have so far is:
PrintWriter itemwriter = new PrintWriter(new FileOutputStream(items));
FileInputStream fstream = new FileInputStream(items);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.contains(name)) {
//do nothing, the item already is in the database.
} else {
itemwriter.println(name);
}
That doesn’t seem to work though. Any suggestions?
You’re trying to read and write to the same file at the same time. While there may be a way of getting that to work, it’s going to be fiddly.
I suggest you read from file A and write to file B – and if you want to effectively replace the input file, then you can do that with a sequence of moves and deletes at the end.
A few other suggestions:
DataInputStream– you’re not using anything from it. Just wrap the input stream directly.FileWriterandFileReaderaccepted encodings in their constructors.)OutputStreamWriter(or something similar) rather thanPrintWriter– currently you’re not going to detect if anything goes wrong when you’re writing.So something like this:
It’s a shame that Java makes this so fiddly with the try/finally blocks. Oh for C#’s
usingstatements…