1

I am trying to enter data into a text file from a java program. The program is executing and showing the output as success but when i open the text file it is still blank. Here is my code

package com.example.ex2;


import java.io.*;  
class Input{  
  public static void main(String args[]){  
   try{  
     FileOutputStream fout=new FileOutputStream("abc.txt");  
     String s="Good MOrning";  

     byte b[]=s.getBytes();  
     fout.write(b);  

     fout.close();  

     System.out.println("success...");  
    }catch(Exception e){

        System.out.println(e);}  
  }  
}

I think i have gone wrong in placing the text file. I have placed it in the default directory.

3
  • 2
    I tested your exact code on my machine and it worked fine. Are you checking the correct file after running the program? Commented Aug 13, 2014 at 7:26
  • can u tell me where have u placed the text file? i guess i have gone wrong there Commented Aug 13, 2014 at 7:27
  • It was placed by default in the same folder as the Java project. Commented Aug 13, 2014 at 7:29

1 Answer 1

1

Your code works fine. Check the correct file.

If you are running from IDE, it will be in the current working directory.

It is always better to your a temp or directory to store files ( certainly not in working dir)

Here is a best practice code. You can tune it further if you wish

public static void main(String args[])
    {
        FileOutputStream fout = null;
        try
        {
            File f = new File("abc.txt");
            if (!f.isFile())
                f.createNewFile();
            fout = new FileOutputStream(f);
            String s = "Good MOrning";

            byte b[] = s.getBytes();
            fout.write(b);

            System.out.println("success... printed at : " + f.getAbsolutePath());
        } catch (Exception e)
        {
            System.out.println(e);
        } finally
        {
            if (null != fout)
                try
                {
                    fout.close();
                } catch (IOException e)
                {
                }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.