1

I'm trying to run some basic java file programming in eclipse:

out=new FileOutputStream("myfile.txt");
p=new PrintStream(out);
p.println("my first file programming in java"); 

I want to write on myfile.txt.

I created myfile.txt in the src but nothing is written after running the program. I tried the same program running in cmd, it works fine.

please let me know the problem

0

3 Answers 3

6

close the FileOutputStream

out=new FileOutputStream("myfile.txt");
p=new PrintStream(out);
p.println("my first file programming in java");
p.close(); 
out.close();
Sign up to request clarification or add additional context in comments.

1 Comment

You should also add p.close() before closing the FileOutputStream
2

At run time, file operations are performed relative to the working directory when absolute paths are not specified so that means a FileOutputStream("myfile.txt") will create the file in the current working directory whatever that is.

If it works in the command line but not in Eclipse then it must mean that src is not your current working folder. I'm guessing the project folder is the current folder.

Do you get an error when running from Eclipse or the program just terminates? If there is no error, then your file is created somewhere else. Do a search on your hard-drive for it.

Just as a test, when running your program from Eclipse, just before the code you posted, add the following and see where it points to:

System.out.println(System.getProperty("user.dir"));

Comments

0

Not sure why I can't add a comment here. @Zimbabao is correct... I just wanted to add that the issue really comes down to flushing. If you look at the source code for PrintStream.close() (actually BufferedWriter), you'll notice that the buffer is flushed before the stream is closed. If your text string was large enough, you might not have even seen this problem. However, closing the stream is just the right thing to do.

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.