Java如何在JDK 7中编写文本文件?

在JDK 7我们可以写出从所有行List的String成使用一个文件Files.write()方法。我们需要提供Path要写入的文件的List,字符串和字符集的。每行都是一个char序列,并按顺序写入文件,每行由平台的行分隔符终止。

让我们看看下面的代码片段:

package org.nhooo.example.io;

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 {

            // 将几行文字写入文件。

            Files.write(file, lines, StandardCharsets.UTF_8);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

此代码段将data.txt在该resources文件夹下创建一个名为的文件。在尝试运行代码之前,请确保该文件夹存在。

以上是 Java如何在JDK 7中编写文本文件? 的全部内容, 来源链接: utcz.com/z/326313.html

回到顶部