Doubt in java programming.

Morningdot Hablu

Morningdot Hablu

@morningdot-6Xuj4M Oct 7, 2024
Hello friend's,
Check out this program.
import java.io.*;
public class r
{
public static void main(String args[])throws IOException
{
try
{
FileReader fr=new FileReader("mohit.txt");
FileWriter fw=new FileWriter("monu.txt");
int s;
while((s=fr.read())!=-1)
{
fw.write(s);
}
}
catch(Exception e)
{
System.out.println("exception occured ");
}
}
}
What's wrong with this one..??

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Saandeep Sreerambatla

    Saandeep Sreerambatla

    @saandeep-sreerambatla-hWHU1M Sep 29, 2010

    You have to use fw.close(); after the while loop.
  • Morningdot Hablu

    Morningdot Hablu

    @morningdot-6Xuj4M Sep 29, 2010

    Yeh it's working.
    .
    Now i comes to the main problem what i faced.
    Check out this program ES
    import java.io.*;
    public class r
    {
    public static void main(String args[])throws IOException
    {
    try
    {
    FileInputStream fr=new FileInputStream("mohit.txt");
    FileOutputStream fw=new FileOutputStream("monu.txt");
    int s,d;
    s=fr.read();
    fw.write(s);
    }
    catch(Exception e)
    {
    System.out.println("exception occured ");
    }
    }
    }
    This program will be written using byte stream in this program i didn't close the streams and it's working but in the case of character stream we must have to close the stream's.
    Can you tell me the reason why..??
  • Saandeep Sreerambatla

    Saandeep Sreerambatla

    @saandeep-sreerambatla-hWHU1M Sep 29, 2010

    This is the information I found from a friend!

    In the FileReader operation the data is written onto Buffer it seems, and you can use flush() or close() for getting the file written!
  • Morningdot Hablu

    Morningdot Hablu

    @morningdot-6Xuj4M Sep 29, 2010

    Thanks ES !!
    I got the answer.
  • Saandeep Sreerambatla

    Saandeep Sreerambatla

    @saandeep-sreerambatla-hWHU1M Sep 30, 2010

    @Mohit:
    Read this point , we need to close the file stream as well.

    Always Close Streams ,Closing a stream when it's no longer needed is very important — so important that CopyBytes uses a finally block to guarantee that both streams will be closed even if an error occurs. This practice helps avoid serious resource leaks.