0

I am creating a file in java using

BufferedWriter out = new BufferedWriter(new FileWriter(FileName)); StringBuffer sb=new StringBuffer(); sb.append("\n"); sb.append("work"); out.write(sb.toString()); out.close(); 

But this file is getting created inside the bin folder of my server.I would like to create this file inside a user-defined folder.

How can it be achieved.

1
  • are you running from an IDE (like eclipse) ? Commented May 7, 2012 at 6:51

2 Answers 2

1

I would like to create this file inside a user-defined folder.

The simplest approach is to specify a fully qualified path name. You could select that as a File and build a new File relative to it:

File directory = new File("/home/jon/somewhere"); File fullPath = new File(directory, fileName); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( (new FileOutputStream(fullPath), charSet)); try { writer.write("\n"); writer.write("work"); } finally { writer.close(); } 

Note:

  • I would suggest using a FileOutputStream wrapped in an OutputStreamWriter instead of using FileWriter, as you can't specify an encoding with FileWriter
  • Use a try/finally block (or try-with-resources in Java 7) so that you always close the writer even if there's an exception.
Sign up to request clarification or add additional context in comments.

3 Comments

What If I want to create a new directory and want to specify the path of this new directory as the location where my file would be stored.?
@Hukamanata: Then you use directory.mkdirs() between the first and second lines...
Thanks a lot for both your answers..It is working in the desired manner.
0

To create a file in a specific directory, you need to specify it in the file name.

Otherwise it will use the current working directory which is likely to be where the program was started from.

BTW: Unless you are using Java 1.4 or older, you can use StringBuilder instead of StringBuffer, although in this case PrintWriter would be even better.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.