简体   繁体   中英

java file programming in eclipse IDE

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

close the FileOutputStream

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

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"));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM