Frederik Witte
Frederik Witte

Reputation: 955

Save in another directory JAVA - Very simple question!

I got a folder called DIR and a subfolder called SUB. the java file i am running is placed in the DIR folder, and now i want to save my small string in a .txt file in the SUB folder.

Could you help me?

Upvotes: 1

Views: 6118

Answers (2)

Gursel Koca
Gursel Koca

Reputation: 21300

Apache org.apache.commons.io.FileUtils class is implemented to reduce amount of boilerplate code..

FileUtils.writeStringToFile(new File("SUB/textFile.txt"),stringData,"UTF-8");

Upvotes: 2

Daniel
Daniel

Reputation: 28104

PrintWriter out = new PrintWriter(
    new OutputStreamWriter(
       new FileOutputStream("SUB/myfile.txt")));
out.println("simpleString);
out.close();

This simple task seems very complicated in Java. The reason is, that you can configure everything on the way from the String to the file. You could e.g. specifiy the encoding of the output file, which defaults to platform encoding (e.g. "win1252" for Windows in most parts of the western hemisphere). To write UTF-8 files use:

PrintWriter out = new PrintWriter(
    new OutputStreamWriter(
        new FileOutputStream("SUB/myfile.txt"),"UTF-8"));
out.println("simpleString);
out.close();

The PrintWriter also has a "flush immediately" option, which is nice for logfiles you want to monitor in the background.

By chaining the IO constructors, you can also increase performance when using a BufferedWriter, because this flushes only to the disk, when a minimum size is reached, or when the stream is closed.

PrintWriter out = new PrintWriter(
   new BufferedWriter(
       new OutputStreamWriter(
           new FileOutputStream("SUB/myfile.txt"),"UTF-8")));
out.println("simpleString);
out.close();

By having to create a FileOutputStream you specify the output should go to the disk, but you can also use any other streamable location, like e.g. an array:

byte[] bytes = new byte[4096];
OutputStream bout = new ByteArrayOutputStream(bout);
PrintWriter out = new PrintWriter(
    new OutputStreamWriter(bout,"UTF-8"));
out.println("simpleString);
out.close();

You will love Javas versatility!

Upvotes: 5

Related Questions