用Java编写文本文件的最简单方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22859453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:26:36  来源:igfitidea点击:

What is the simplest way to write a text file in Java?

javafiletext

提问by Georgi Koemdzhiev

I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D

我想知道用 Java 编写文本文件的最简单(也是最简单)的方法是什么。请简单点,因为我是初学者:D

I searched the web and found this code, but I understand 50% of it.

我在网上搜索并找到了这段代码,但我理解了其中的 50%。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {
public static void main(String[] args) {
    try {

        String content = "This is the content to write into file";

        File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

}

采纳答案by dazito

With Java 7 and up, a one liner using Files:

对于 Java 7 及更高版本,使用Files 的单行:

String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());

回答by newuser

Appending the file FileWriter(String fileName, boolean append)

附加文件FileWriter(String fileName, boolean append)

try {   // this is for monitoring runtime Exception within the block 

        String content = "This is the content to write into file"; // content to write into the file

        File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here

        // if file doesnt exists, then create it
        if (!file.exists()) {   // checks whether the file is Exist or not
            file.createNewFile();   // here if file not exist new file created 
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
        BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
        bw.write(content); // write method is used to write the given content into the file
        bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect. 

        System.out.println("Done");

    } catch (IOException e) { // if any exception occurs it will catch
        e.printStackTrace();
    }

回答by Jakub H

You can use FileUtilsfrom Apache Commons:

您可以使用Apache Commons 中的FileUtils

import org.apache.commons.io.FileUtils;

final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);

回答by Dilip Kumar

You could do this by using JAVA 7new File API.

您可以通过使用JAVA 7new来做到这一点File API

code sample: `

代码示例:`

public class FileWriter7 {
    public static void main(String[] args) throws IOException {
        List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
        String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
        writeSmallTextFile(lines, filepath);
    }

    private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
        Path path = Paths.get(aFileName);
        Files.write(path, aLines, StandardCharsets.UTF_8);
    }
}

`

`

回答by Kumaran Ramanujam

Your code is the simplest. But, i always try to optimize the code further. Here is a sample.

你的代码是最简单的。但是,我总是尝试进一步优化代码。这是一个示例。

try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
    bw.write("Hello, This is a test message");
    bw.close();
    }catch (FileNotFoundException ex) {
    System.out.println(ex.toString());
    }

回答by Laszlo Lugosi

Files.write() the simple solution as @Dilip Kumar said. I used to use that way untill I faced an issue, can not affect line separator (Unix/Windows) CR LF.

Files.write() 是@Dilip Kumar 所说的简单解决方案。我曾经使用这种方式,直到我遇到问题,无法影响行分隔符(Unix/Windows)CR LF。

So now I use a Java 8 stream file writing way, what allows me to manipulate the content on the fly. :)

所以现在我使用 Java 8 流文件写入方式,什么让我可以即时操作内容。:)

List<String> lines = Arrays.asList(new String[] { "line1", "line2" });

Path path = Paths.get(fullFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {   
    writer.write(lines.stream()
                      .reduce((sum,currLine) ->  sum + "\n"  + currLine)
                      .get());
}     

In this way, I can specify the line separator or I can do any kind of magic like TRIM, Uppercase, filtering etc.

通过这种方式,我可以指定行分隔符,或者我可以做任何类型的魔术,如 TRIM、大写、过滤等。

回答by ruks

File file = new File("path/file.name");
IOUtils.write("content", new FileOutputStream(file));

IOUtils also can be used to write/read files easily with java 8.

IOUtils 也可用于使用 java 8 轻松写入/读取文件。

回答by laughing buddha

String content = "your content here";
Path path = Paths.get("/data/output.txt");
if(!Files.exists(path)){
    Files.createFile(path);
}
BufferedWriter writer = Files.newBufferedWriter(path);
writer.write(content);

回答by Praveen

In Java 11or Later, writeStringcan be used from java.nio.file.Files,

Java 11或以后,writeString可以使用从java.nio.file.Files

String content = "This is my content";
String fileName = "myFile.txt";
Files.writeString(Paths.get(fileName), content); 

With Options:

有选项:

Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)

More documentation about the java.nio.file.Filesand StandardOpenOption

有关java.nio.file.FilesStandardOpenOption 的更多文档