Reputation: 141
I have a txt with a list of words. Every word that has 14 letters, starts with a "M" and has a "n" at the eighth position. Should be very simple, but there are actualy a few problems. Here is my code:
public static void main(String[] args) throws IOException {
BufferedReader buff = new BufferedReader(new FileReader("C:/users/admin/Documents/Auslese.txt"));
BufferedWriter buff2 = new BufferedWriter(new FileWriter("C:/users/admin/Documents/Eingegrenzt.txt"));
String text = buff.readLine();
char buchstabe, buchstabe2;
while(text != null){
if(text.length() == 14){
buchstabe = text.charAt(0);
buchstabe2 = text.charAt(7);
if((buchstabe == 'M' || buchstabe == 'm') && buchstabe2 == 'n'){
buff2.write(text);
buff2.newLine();
}}
text = buff.readLine();
}
}
There are actually a few words that match these conditions, but no word will be written in the second file after execution of the code.
For example the line text.length() == 14
doesn't work, even though there are words with 14 letters. If I choose text.length() > 13
, then it works.
Or the condition with the letter 'n'. Without it (and length > 13
) it works fine, but after adding this line there are no words in the file again (even though for example every word starting with "Marathon" should be fine).
I hope, that somebody here can help me :/.
Upvotes: 1
Views: 40
Reputation: 5049
Try closing the buffers. They might not be flushed, hence, nothing in the file. That's more or less how the BufferedWriter
works.
Put buff.close()
and buff2.close()
at the end of your program.
Also, always close your buffers/files/streams within a finally
block. That way it will always be sure the buffers are closed.
Upvotes: 3