用Java创建和写入(文本)文件的最简单方法是什么?


当前回答

使用Google的Guava库,我们可以创建和写入文件容易地

package com.zetcode.writetofileex;

import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;

public class WriteToFileEx {

    public static void main(String[] args) throws IOException {

        String fileName = "fruits.txt";
        File file = new File(fileName);

        String content = "banana, orange, lemon, apple, plum";

        Files.write(content.getBytes(), file);
    }
}

该示例在项目根目录中创建一个新的fruits.txt文件。

其他回答

由于作者没有说明他们是否需要针对已经EoL的Java版本的解决方案(Sun和IBM都提供了,从技术上讲,这些版本是最广泛的JVM),并且由于大多数人似乎在作者的问题被指定为文本(非二进制)文件之前就已经回答了这个问题,所以我决定提供我的答案。


首先,Java 6通常已经到了生命的尽头,由于作者没有指定他需要遗留兼容性,我想这自动意味着Java 7或更高版本(Java 7尚未被IBM EoL)。因此,我们可以看看文件I/O教程:https://docs.oracle.com/javase/tutorial/essential/io/legacy.html

在Java SE 7发布之前,Java.io.File类是用于文件I/O的机制,但它有几个缺点。许多方法在失败时不会抛出异常,所以无法获得有用的错误消息。例如,如果文件删除失败,程序将收到“删除失败”,但不知道是否是因为文件不存在,用户不存在具有权限,或者存在其他问题。重命名方法跨平台工作不一致。没有真正的支持用于符号链接。需要对元数据提供更多支持,例如文件权限、文件所有者和其他安全属性。访问文件元数据效率低下。许多File方法都无法扩展。通过服务器请求大型目录列表可能会导致悬挂大目录还可能导致内存资源问题,导致拒绝服务。无法写入可以递归遍历文件树并做出响应的可靠代码如果存在循环符号链接,则可以适当。

哦,好吧,这排除了java.io.File。如果无法写入/附加文件,您可能甚至无法知道原因。


我们可以继续查看教程:https://docs.oracle.com/javase/tutorial/essential/io/file.html#common

如果您有所有要提前写入(附加)到文本文件的行,建议的方法是https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path java.lang.Iterable-java.nio.charset.charset java.nio.file OpenOption-

下面是一个示例(简化):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, StandardCharsets.UTF_8);

另一个示例(附加):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE);

如果您想按原样写入文件内容:https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedWriter-java.nio.file.Path java.nio.charset.charset java.nio.file OpenOption-

简化示例(Java 8或更高版本):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file)) {
    writer.append("Zero header: ").append('0').write("\r\n");
    [...]
}

另一个示例(附加):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
    writer.write("----------");
    [...]
}

这些方法需要作者尽可能少的努力,并且在写入[文本]文件时应优先于其他所有方法。

我认为这是最短的路:

FileWriter fr = new FileWriter("your_file_name.txt"); // After '.' write
// your file extention (".txt" in this case)
fr.write("Things you want to write into the file"); // Warning: this will REPLACE your old file content!
fr.close();

如果出于某种原因想要将创建和编写行为分开,那么Java中的touch等价物是

try {
   //create a file named "testfile.txt" in the current working directory
   File myFile = new File("testfile.txt");
   if ( myFile.createNewFile() ) {
      System.out.println("Success!");
   } else {
      System.out.println("Failure!");
   }
} catch ( IOException ioe ) { ioe.printStackTrace(); }

createNewFile()执行存在性检查,并自动创建文件。例如,如果您希望在写入文件之前确保自己是文件的创建者,这可能很有用。

用Java创建和写入文件的一种非常简单的方法:

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

public class CreateFiles {

    public static void main(String[] args) {
        try{
            // Create new file
            String content = "This is the content to write into create file";
            String path="D:\\a\\hi.txt";
            File file = new File(path);

            // If file doesn't exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

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

            // Write in file
            bw.write(content);

            // Close connection
            bw.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}

这里我们将字符串输入到文本文件中:

String content = "This is the content to write into a file";
File file = new File("filename.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close(); // Be sure to close BufferedWriter

我们可以轻松地创建一个新文件并向其中添加内容。