简体   繁体   中英

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?

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 eg specifiy the encoding of the output file, which defaults to platform encoding (eg "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 eg 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!

实现了Apache org.apache.commons.io.FileUtils类以减少样板代码的数量。

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

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