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


当前回答

至少有几种方法可以创建文件并写入其中:

小文件(1.7)

您可以使用其中一种写入方法将字节或行写入文件。

Path file = Paths.get("path-to-file");
byte[] buf = "text-to-write-to-file".getBytes();
Files.write(file, buf);

这些方法为您处理大部分工作,例如打开和关闭流,但不适用于处理大型文件。

使用缓冲流I/O写入更大的文件(1.7)

java.nio.file包支持通道I/O,它可以在缓冲区中移动数据,绕过一些可能阻塞流I/O的层。

String s = "much-larger-text-to-write-to-file";
try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
    writer.write(s, 0, s.length());
}

这种方法由于其高效的性能,特别是在完成大量写入操作时,是优先的。缓冲操作具有这种效果,因为它们不需要为每个字节调用操作系统的写入方法,从而减少了昂贵的I/O操作。

使用NIOAPI复制(并创建一个新的)带有输出流的文件(1.7)

Path oldFile = Paths.get("existing-file-path");
Path newFile = Paths.get("new-file-path");
try (OutputStream os = new FileOutputStream(newFile.toFile())) {
    Files.copy(oldFile, os);
}

还有其他方法允许将输入流中的所有字节复制到文件中。

FileWriter(文本)(<1.7)

直接写入文件(性能较低),仅当写入次数较少时才应使用。用于将面向字符的数据写入文件。

String s= "some-text";
FileWriter fileWriter = new FileWriter("C:\\path\\to\\file\\file.txt");
fileWriter.write(fileContent);
fileWriter.close();

FileOutputStream(二进制)(<1.7)

FileOutputStream用于写入原始字节流,如图像数据。

byte data[] = "binary-to-write-to-file".getBytes();
FileOutputStream out = new FileOutputStream("file-name");
out.write(data);
out.close();

使用这种方法,应该考虑始终写入字节数组,而不是一次写入一个字节。加速可能非常显著-高达10倍或更高。因此,建议尽可能使用write(byte[])方法。

其他回答

如果您希望获得相对轻松的体验,还可以查看Apache Commons IO包,更具体地说是FileUtils类。

永远不要忘记检查第三方库。用于日期操作的Joda Time、用于常见字符串操作的Apache Commons Lang StringUtils等可以使代码更可读。

Java是一种很棒的语言,但标准库有时有点低级。功能强大,但级别较低。

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

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

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

用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);
        }
    }
}

我认为这是最短的路:

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();

最好的方法是使用Java7:Java7引入了一种处理文件系统的新方法,以及一个新的实用程序类—Files。使用Files类,我们还可以创建、移动、复制、删除文件和目录;它还可以用于读取和写入文件。

public void saveDataInFile(String data) throws IOException {
    Path path = Paths.get(fileName);
    byte[] strToBytes = data.getBytes();

    Files.write(path, strToBytes);
}

使用FileChannel写入如果您正在处理大型文件,FileChannel可以比标准IO更快。以下代码使用FileChannel将字符串写入文件:

public void saveDataInFile(String data) 
  throws IOException {
    RandomAccessFile stream = new RandomAccessFile(fileName, "rw");
    FileChannel channel = stream.getChannel();
    byte[] strBytes = data.getBytes();
    ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
    buffer.put(strBytes);
    buffer.flip();
    channel.write(buffer);
    stream.close();
    channel.close();
}

使用DataOutputStream写入

public void saveDataInFile(String data) throws IOException {
    FileOutputStream fos = new FileOutputStream(fileName);
    DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
    outStream.writeUTF(data);
    outStream.close();
}

使用FileOutputStream写入

现在让我们看看如何使用FileOutputStream将二进制数据写入文件。以下代码转换String int字节,并使用FileOutputStream将字节写入文件:

public void saveDataInFile(String data) throws IOException {
    FileOutputStream outputStream = new FileOutputStream(fileName);
    byte[] strToBytes = data.getBytes();
    outputStream.write(strToBytes);

    outputStream.close();
}

使用PrintWriter写入我们可以使用PrintWriter将格式化文本写入文件:

public void saveDataInFile() throws IOException {
    FileWriter fileWriter = new FileWriter(fileName);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.print("Some String");
    printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
    printWriter.close();
}

使用BufferedWriter写入:使用BufferedWriter将字符串写入新文件:

public void saveDataInFile(String data) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
    writer.write(data);

    writer.close();
}

将字符串附加到现有文件:

public void saveDataInFile(String data) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
    writer.append(' ');
    writer.append(data);

    writer.close();
}