jdk7 new api

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
 
public class WriteTextFile {
    public static void main(String[] args) {
        Path file = Paths.get("D:\\resources\\data.txt");
 
        List<String> lines = new ArrayList<>();
        lines.add("Lorem Ipsum is simply dummy text of the printing ");
        lines.add("and typesetting industry. Lorem Ipsum has been the ");
        lines.add("industry's standard dummy text ever since the 1500s, ");
        lines.add("when an unknown printer took a galley of type and ");
        lines.add("scrambled it to make a type specimen book.");
 
        try {
            //
            // Write lines of text to a file.
            //
            Files.write(file, lines, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
This post shows you how to write a file using the JDK 7 Path:

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;

public class Main {

    public static void main(String[] args) {
        Path myDir = Paths.get("D:/data");

        //use the above Path instance as an anchor
        Path writeFile = myDir.resolve("message.txt");

        try {
            "old" Java 7 
            OutputStream out = writeFile.newOutputStream();
            BufferedWriter br = new BufferedWriter(new OutputStreamWriter(out));
            br.write("This is a text file written through Path API!");
            br.write("\n");

            br.flush();
            br.close();
            out.flush();
            out.close();

            //new Java 7
            BufferedWriter br = Files.newBufferedWriter(writeFile,               
               Charset.forName("UTF-8"), 
               new OpenOption[] {StandardOpenOption.WRITE});
            br.write("This is a text file written through Path API!");
            br.write("\n");

            br.flush();
            br.close();
        } catch (IOException e) {
            System.err.println("Error: " + e.toString());
        }
    }
}

There are several options you can use when opening a file – conforming to documentation, we have:
•  StandardOpenOption.CREATE (default behavior for writes)
Create a file if it does not already exist.
•  StandardOpenOption.CREATE_NEW
Expect that the file does not already exist, and create it. Throw an exception if the file does already exist.
•  StandardOpenOption.APPEND
Write new data to the end of the existing file.
•  StandardOpenOption.TRUNCATE_EXISTING (default for writes)
Remove all data from an existing file when opening it.
•  StandardOpenOption.NOFOLLOW_LINKS
Throw an exception if it is necessary to resolve a symbolic link to open a file.
•  StandardOpenOption.SPARSE
Suggest that the file will be sparse so the underlying operating system can optimize for that use case. File systems that don't support sparse files will ignore this hint.
•  StandardOpenOption.DSYNC
Write data to the underlying disk immediately. Do not use native buffering. This does not affect buffering internal to Java, such as that performed by BufferedInputStream and BufferedWriter.
•  StandardOpenOption.SYNC
Write data and metadata (attributes) to the underlying disk immediately.
•  StandardOpenOption.READ
Open for reading.
•  StandardOpenOption.WRITE
Open for writing.

Per example, you can use these options to explicitly open a file for reading, like this:

OutputStream out = writeFile.newOutputStream(new OpenOption[] 
                                             {StandardOpenOption.WRITE});

Note: Not all of these are mutually exclusive. You can use several when opening a file.
1 comment:
Anonymous said...

The java.nio.file.Files class defines the newBufferedWriter method that would shorten this example, eg:

try (BufferedWriter writer = Files.newBufferedWriter(writeFile, cs)) {
...
}

Alternatively, just use the Files.write method, eg:

Files.write(writeFile, Arrays.asList("This is text"), Charset.forName("UTF-8"))


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值