开发者

Checking a file for a certain string in Java

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 itemw开发者_高级运维riter = 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:

  • You should have try/finally blocks to close both the input and the output at the end.
  • You don't need to use a DataInputStream - you're not using anything from it. Just wrap the input stream directly.
  • I suggest you specify the encoding explicitly both for input and output rather than trusting the default encoding. (I wish FileWriter and FileReader accepted encodings in their constructors.)
  • It's more robust to use OutputStreamWriter (or something similar) rather than PrintWriter - currently you're not going to detect if anything goes wrong when you're writing.

So something like this:

// Ideally have this as a constant somewhere.
Charset utf8 = Charset.forName("UTF-8");

BufferedReader reader = new BufferedReader(new InputStreamReader(
    new FileInputStream(inputFile), utf8);
try {
  try {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(outputFile), utf8);

    String line;
    while ((line = reader.readLine()) != null) {
      if (!line.contains(name)) {
        writer.write(line);
        writer.newLine();
      }
    }
  } finally {
    writer.close();
  }
} finally {
  reader.close();
}
// Now if you want to shift files around, do it here

It's a shame that Java makes this so fiddly with the try/finally blocks. Oh for C#'s using statements...


First of all you shounld not be using Streams. Use FileReaders and FileWriters.

If you need more help post your SSCCE showing the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜