0

Here is my Java code.

File file = new File(path);
StringWriter sw = new StringWriter();
//Do something.
out.println(sw.toString()); //Works fine; prints.
try {
        FileUtils.writeStringToFile(file, sw.toString(), "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException( e );
    }

I don't already have the file created, and neither is it creating it after the execution. How can I do this?

1
  • 3
    So... do you get an exception? Commented Sep 4, 2012 at 11:15

3 Answers 3

2

See File.createNewFile().

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. ..

As mentioned by @JohnWatts in comments:

..both PrintWriter and your code create the file, but pre-1.3 FileUtils.writeStringToFile does not.

Sign up to request clarification or add additional context in comments.

8 Comments

If he is using Apache Commons FileUtils (with v >= 1.3), then he is already having the file created if necessary, including parent dirs. So there is no need for File.createNewFile().
@Andrew Thompson what if later i want to use the name of the file; what is the name of the file created int his case.? thanks
@Andrew Thompson i.e. where exactly am i specifying the path?
@Kraken If you are using FileUtils with a version greater than 1.3, then I think you can ignore this answer as your file should be created automatically for you. Please post the exception you are no doubt receiving so we know why the writing to file has failed.
@Kraken What version of the FileUtils API are you using? I am getting some down votes for suggesting a J2SE method that would seem to solve the stated problem.
|
1

Don't use StringWriter, use PrintWriter instead:

 PrintWriter w = new PrintWriter(file);
 w.print(string);
 w.flush();
 w.close()

2 Comments

This is possible, but the posted code is simpler and should work. Let's try to find out why it fails.
If you use this answer, specify the encoding in the Writer constructor. Otherwise the encoding used will be platform dependent. The only Writer I can see that let's you do this is OutputStreamWriter.
1

I checked the code and it works.

The only problem that I could think of is path value. Try with hardcoded path value. Because I doubt file is getting created and you are not able to find it.

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.