I wanted to write a java program that will copy all the words starting with a vowel from a file and store those words in another file separated by spaces to out.txt file. my code working only for the last word from the loop.
package findvowelwords;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FindVowelWords {
public static void main(String[] args) throws IOException
{
File f1=new File("input.txt"); //Creation of File Descriptor for input file
String[] words=null; //Intialize the word Array
FileReader fr = new FileReader(f1); //Creation of File Reader object
BufferedReader br = new BufferedReader(fr); //Creation of BufferedReader object
String s;
int flag=0; //Intialize the flag variable
while((s=br.readLine())!=null)
{
words=s.split(" "); //Split the word using space
for(int i=0;i<words.length;i++)
{
for(int j=0;j<words[i].length();j++)
{
char ch=words[i].charAt(j); //Read the word char by char
if(ch == 'a' || ch == 'e' || ch == 'i' ||ch == 'o' || ch == 'u') //Checking for vowels
{
flag=1; //If vowels persent set flag as one
}
break;
}
if(flag==1)
{
System.out.println(words[i]); //Print the vowels word
try
{
FileWriter fw = new FileWriter("out.txt");
fw.write(words[i]);
fw.close();
}
catch(Exception e)
{
System.out.print("Error : "+e);
}
}
flag=0;
}
}
}
}
I have to transfer the words from words[I] to a global string variable and then I have to input the string to fw.write(Here);.
But I failed to do that. Also, I know the Try code I have to write out of the while loop I tried many times but failed.
try
{
FileWriter fw = new FileWriter("out.txt");
fw.write(words[i]);
fw.close();
}
catch(Exception e)
{
System.out.print("Error : "+e);
}
My current file’s output:
Compile Output is:
Out.txt file should like this
Please, can you help me with this??
>Solution :
You are opening the file in in write mode. you have to open the file in append mode.
Solution:
Change FileWriter fw = new FileWriter("out.txt");
To: FileWriter fw = new FileWriter("out.txt", true);
Read this:
FileWriter(String fileName, boolean append)



