如何在 Java 中创建文件并写入文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2885173/
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 14:03:22  来源:igfitidea点击:

How do I create a file and write to it in Java?

javafile-io

提问by Drew Johnson

What's the simplest way to create and write to a (text) file in Java?

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

采纳答案by Michael

Note that each of the code samples below may throw IOException. Try/catch/finally blocks have been omitted for brevity. See this tutorialfor information about exception handling.

请注意,下面的每个代码示例都可能会抛出IOException. 为简洁起见,已省略 Try/catch/finally 块。有关异常处理的信息,请参阅本教程

Note that each of the code samples below will overwrite the file if it already exists

请注意,如果文件已经存在,下面的每个代码示例都将覆盖该文件

Creating a text file:

创建文本文件:

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Creating a binary file:

创建二进制文件:

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

Java 7+users can use the Filesclass to write to files:

Java 7+用户可以使用Files该类写入文件:

Creating a text file:

创建文本文件:

List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Creating a binary file:

创建二进制文件:

byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);

回答by Bozho

In Java 7 and up:

在 Java 7 及更高版本中:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(
              new FileOutputStream("filename.txt"), "utf-8"))) {
   writer.write("something");
}

There are useful utilities for that though:

不过,有一些有用的实用程序:

Note also that you canuse a FileWriter, but it uses the default encoding, which is often a bad idea - it's best to specify the encoding explicitly.

另请注意,您可以使用 a FileWriter,但它使用默认编码,这通常是一个坏主意 - 最好明确指定编码。

Below is the original, prior-to-Java 7 answer

以下是 Java 7 之前的原始答案



Writer writer = null;

try {
    writer = new BufferedWriter(new OutputStreamWriter(
          new FileOutputStream("filename.txt"), "utf-8"));
    writer.write("Something");
} catch (IOException ex) {
    // Report
} finally {
   try {writer.close();} catch (Exception ex) {/*ignore*/}
}

See also: Reading, Writing, and Creating Files(includes NIO2).

另请参阅:读取、写入和创建文件(包括 NIO2)。

回答by Eric Petroelje

public class Program {
    public static void main(String[] args) {
        String text = "Hello world";
        BufferedWriter output = null;
        try {
            File file = new File("example.txt");
            output = new BufferedWriter(new FileWriter(file));
            output.write(text);
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
          if ( output != null ) {
            output.close();
          }
        }
    }
}

回答by extraneon

If you wish to have a relatively pain-free experience you can also have a look at the Apache Commons IO package, more specifically the FileUtilsclass.

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

Never forget to check third-party libraries. Joda-Timefor date manipulation, Apache Commons Lang StringUtilsfor common string operations and such can make your code more readable.

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

Java is a great language, but the standard library is sometimes a bit low-level. Powerful, but low-level nonetheless.

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

回答by Mark Peters

If you for some reason want to separate the act of creating and writing, the Java equivalent of touchis

如果您出于某种原因想要将创建和编写的行为分开,那么 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()does an existence check and file create atomically. This can be useful if you want to ensure you were the creator of the file before writing to it, for example.

createNewFile()以原子方式进行存在检查和文件创建。例如,如果您想在写入文件之前确保您是文件的创建者,这会很有用。

回答by Draeven

Here's a little example program to create or overwrite a file. It's the long version so it can be understood more easily.

这是一个创建或覆盖文件的小示例程序。这是长版本,因此可以更容易地理解。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class writer {
    public void writing() {
        try {
            //Whatever the file path is.
            File statText = new File("E:/Java/Reference/bin/images/statsTest.txt");
            FileOutputStream is = new FileOutputStream(statText);
            OutputStreamWriter osw = new OutputStreamWriter(is);    
            Writer w = new BufferedWriter(osw);
            w.write("POTATO!!!");
            w.close();
        } catch (IOException e) {
            System.err.println("Problem writing to the file statsTest.txt");
        }
    }

    public static void main(String[]args) {
        writer write = new writer();
        write.writing();
    }
}

回答by icl7126

Use:

用:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) {
    writer.write("text to write");
} 
catch (IOException ex) {
    // Handle me
}  

Using try()will close stream automatically. This version is short, fast (buffered) and enables choosing encoding.

使用try()将自动关闭流。此版本简短、快速(缓冲)并且可以选择编码。

This feature was introduced in Java 7.

这个特性是在 Java 7 中引入的。

回答by icza

If you already have the content you want to write to the file (and not generated on the fly), the java.nio.file.Filesaddition in Java 7 as part of native I/O provides the simplest and most efficient way to achieve your goals.

如果您已经拥有要写入文件的内容(而不是动态生成的),java.nio.file.FilesJava 7 中作为本机 I/O 的一部分的添加提供了实现目标的最简单和最有效的方法。

Basically creating and writing to a file is one line only, moreover one simple method call!

基本上创建和写入文件只有一行,而且是一个简单的方法调用

The following example creates and writes to 6 different files to showcase how it can be used:

以下示例创建并写入 6 个不同的文件以展示如何使用它:

Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("1st line", "2nd line");
byte[] data = {1, 2, 3, 4, 5};

try {
    Files.write(Paths.get("file1.bin"), data);
    Files.write(Paths.get("file2.bin"), data,
            StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    Files.write(Paths.get("file3.txt"), "content".getBytes());
    Files.write(Paths.get("file4.txt"), "content".getBytes(utf8));
    Files.write(Paths.get("file5.txt"), lines, utf8);
    Files.write(Paths.get("file6.txt"), lines, utf8,
            StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
    e.printStackTrace();
}

回答by iKing

Here we are entering a string into a text file:

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

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

We can easily create a new file and add content into it.

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

回答by aashima

To create file without overwriting existing file:

要在不覆盖现有文件的情况下创建文件:

System.out.println("Choose folder to create file");
JFileChooser c = new JFileChooser();
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
c.showOpenDialog(c);
c.getSelectedFile();
f = c.getSelectedFile(); // File f - global variable
String newfile = f + "\hi.doc";//.txt or .doc or .html
File file = new File(newfile);

try {
    //System.out.println(f);
    boolean flag = file.createNewFile();

    if(flag == true) {
        JOptionPane.showMessageDialog(rootPane, "File created successfully");
    }
    else {
        JOptionPane.showMessageDialog(rootPane, "File already exists");
    }
    /* Or use exists() function as follows:
        if(file.exists() == true) {
            JOptionPane.showMessageDialog(rootPane, "File already exists");
        }
        else {
            JOptionPane.showMessageDialog(rootPane, "File created successfully");
        }
    */
}
catch(Exception e) {
    // Any exception handling method of your choice
}