Question

In the following program, I get input from console and store the odd number of characters and even number of characters in a separate file. But when I run the program, I get only one character.

For example, if I give Hello as input and if I read from the even file, it displays only 'o'.

import java.io.*;
import java.util.*;

class OddEvenFile
{
public static void main(String args[])throws IOException
{
    char tmp;
    String str;
    StringBuffer rese=new StringBuffer();
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    FileInputStream fine=new FileInputStream("C:\\Users\\Siva\\Documents\\Java\\Even.txt");
    FileInputStream fino=new FileInputStream("C:\\Users\\Siva\\Documents\\Java\\Odd.txt");
    FileOutputStream foute=new FileOutputStream("C:\\Users\\Siva\\Documents\\Java\\Even.txt");
    FileOutputStream fouto=new FileOutputStream("C:\\Users\\Siva\\Documents\\Java\\Odd.txt");
    System.out.print("\nEnter a String :");
    str=br.readLine();
    System.out.print("\n Length :"+str.length());
    for(int i=1;i<str.length();i++)
    {

        char c=str.charAt(i);
        if(i%2 == 0)
            foute.write(c);
        else
            fouto.write(c);
    }
    while(fine.read()!=-1)
    {
        tmp=(char)fine.read();
        //tmp=String.valueOf()
        rese.append(tmp);
    }
    System.out.print("In even file :"+(rese.toString()));
}
}
Was it helpful?

Solution

Try this: First write to the files, then close the files, and then open the new files:

public static void main(String args[])throws IOException
{
    char tmp;
    String str;
    StringBuffer rese=new StringBuffer();
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    FileOutputStream foute=new FileOutputStream("Even.txt");
    FileOutputStream fouto=new FileOutputStream("Odd.txt");
    System.out.print("\nEnter a String :");
    str=br.readLine();
    System.out.print("\n Length : "+str.length() + "\n");

    for(int i = 0;i < str.length(); i++)
    {
        char c=str.charAt(i);
        if(i%2 == 0)
            foute.write(c);
        else
            fouto.write(c);
    }

    foute.close();
    fouto.close();

    FileInputStream fine=new FileInputStream("Even.txt");
    FileInputStream fino=new FileInputStream("Odd.txt");

    String s = "";
    while(fine.available() > 0)
    {
        s += (char) fine.read();
    }

    fine.close();
    fino.close();
    System.out.print("In even file : " + s);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top