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


当前回答

有许多方法可以写入文件。每种方法都有其优点,而且在给定的场景中,每种方法可能都是最简单的。

这个答案以Java 8为中心,并试图涵盖Java专业考试所需的所有细节。涉及的课程包括:

.
├── OutputStream
│   └── FileOutputStream
├── Writer
│   ├── OutputStreamWriter
│   │   └── FileWriter
│   ├── BufferedWriter
│   └── PrintWriter (Java 5+)
└── Files (Java 7+)

写入文件有5种主要方式:

┌───────────────────────────┬────────────────────────┬─────────────┬──────────────┐
│                           │       Buffer for       │ Can specify │   Throws     │
│                           │      large files?      │  encoding?  │ IOException? │
├───────────────────────────┼────────────────────────┼─────────────┼──────────────┤
│ OutputStreamWriter        │ Wrap in BufferedWriter │ Y           │ Y            │
│ FileWriter                │ Wrap in BufferedWriter │             │ Y            │
│ PrintWriter               │ Y                      │ Y           │              │
│ Files.write()             │                        │ Y           │ Y            │
│ Files.newBufferedWriter() │ Y                      │ Y           │ Y            │
└───────────────────────────┴────────────────────────┴─────────────┴──────────────┘

每个都有其独特的优势:

OutputStreamWriter-Java 5之前最基本的方法FileWriter–可选附加构造函数参数PrintWriter–多种方法Files.write()–在一次调用中创建并写入文件Files.newBufferedWriter()–便于编写大型文件

以下是每一项的详细信息。

文件输出流

此类用于写入原始字节流。下面的所有Writer方法都依赖于这个类,无论是显式的还是隐藏式的。

try (FileOutputStream stream = new FileOutputStream("file.txt");) {
    byte data[] = "foo".getBytes();
    stream.write(data);
} catch (IOException e) {}

注意,trywithresources语句负责stream.close(),关闭流会刷新它,就像stream.flush()一样。

输出StreamWriter

此类是从字符流到字节流的桥梁。它可以包装FileOutputStream,并写入字符串:

Charset utf8 = StandardCharsets.UTF_8;
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File("file.txt")), utf8)) {
    writer.write("foo");
} catch (IOException e) {}

缓冲写入程序

此类将文本写入字符输出流,缓冲字符,以便有效地写入单个字符、数组和字符串。

它可以包装OutputStreamWriter:

try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("file.txt"))))) {
    writer.write("foo");
    writer.newLine();  // method provided by BufferedWriter
} catch (IOException e) {}

在Java5之前,这是处理大型文件的最佳方法(具有常规的try/catch块)。

字符输出流

这是OutputStreamWriter的子类,是编写字符文件的便利类:

boolean append = false;
try(FileWriter writer = new FileWriter("file.txt", append) ){
    writer.write("foo");
    writer.append("bar");
} catch (IOException e) {}

关键的好处是它有一个可选的附加构造函数参数,该参数决定它是附加到现有文件还是覆盖现有文件。注意,append/overwrite行为不受write()和append()方法的控制,它们的行为方式几乎相同。

注意:

没有缓冲,但为了处理大型文件,可以将其包装在BufferedWriter中。FileWriter使用默认编码。通常最好明确指定编码

字符打印流

此类将对象的格式化表示打印到文本输出流。实际上,它与上面的BufferedWriter方法(新的BufferedWriter(新的OutputStreamWriter(新的FileOutputStream(…)))相同。PrintWriter是在Java5中引入的,作为调用此习惯用法的方便方法,并添加了printf()和println()等其他方法。

此类中的方法不会引发I/O异常。您可以通过调用checkError()来检查错误。PrintWriter实例的目标可以是File、OutputStream或Writer。以下是写入文件的示例:

try (PrintWriter writer = new PrintWriter("file.txt", "UTF-8")) {
    writer.print("foo");
    writer.printf("bar %d $", "a", 1);
    writer.println("baz");
} catch (FileNotFoundException e) {
} catch (UnsupportedEncodingException e) {}

当写入OutputStream或Writer时,有一个可选的autoFlush构造函数参数,默认为false。与FileWriter不同,它将覆盖任何现有文件。

文件.write()

Java7引入了Java.nio.file.Files.Files.write(),它允许您在一次调用中创建和写入文件。

@icza的答案显示了如何使用这种方法。几个例子:

Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("foo", "bar");

try {
    Files.write(Paths.get("file.txt"), "foo".getBytes(utf8));
    Files.write(Paths.get("file2.txt"), lines, utf8);
} catch (IOException e) {}

这不涉及缓冲区,因此不适用于大型文件。

文件.newBufferedWriter()

Java 7还引入了Files.newBufferedWriter(),这使得获取BufferedWriter变得容易:

Charset utf8 = StandardCharsets.UTF_8;
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("file.txt"), utf8)) {
    writer.write("foo");
} catch (IOException e) {}

这与PrintWriter类似,缺点是没有PrintWriter的方法,好处是它不会吞下异常。

其他回答

以下是用Java创建和编写文件的一些可能方法:

使用FileOutputStream

try {
  File fout = new File("myOutFile.txt");
  FileOutputStream fos = new FileOutputStream(fout);
  BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
  bw.write("Write somthing to the file ...");
  bw.newLine();
  bw.close();
} catch (FileNotFoundException e){
  // File was not found
  e.printStackTrace();
} catch (IOException e) {
  // Problem when writing to the file
  e.printStackTrace();
}

使用FileWriter

try {
  FileWriter fw = new FileWriter("myOutFile.txt");
  fw.write("Example of content");
  fw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

使用PrintWriter

try {
  PrintWriter pw = new PrintWriter("myOutFile.txt");
  pw.write("Example of content");
  pw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

使用OutputStreamWriter

try {
  File fout = new File("myOutFile.txt");
  FileOutputStream fos = new FileOutputStream(fout);
  OutputStreamWriter osw = new OutputStreamWriter(fos);
  osw.write("Soe content ...");
  osw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

有关如何在Java中读写文件的详细信息,请参阅本教程。

在Java 7及以上版本中:

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

但有一些有用的实用程序:

来自commons io的FileUtils.writeStringtoFile(..)来自番石榴的文件.write(..)

还要注意,您可以使用FileWriter,但它使用默认编码,这通常是一个坏主意-最好显式指定编码。

以下是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*/}
}

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

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 ) {
            try {
                output.close();
            }catch (IOException e){
                e.printStackTrace();
            }
          }
        }
    }
}

以下是编写文件的代码,也在退出帮助内容网页时删除:

public String writeHelpContent(String filePath, String helpPageContent) throws IOException{
        logger.info("HowToUseRiskOfficeHelpService - writeHelpContent start");
        File file = new File(filePath);
        try(FileWriter fw = new FileWriter(file);){
            file.deleteOnExit();
            if(file.createNewFile()) {
                logger.info("HowToUseRiskOfficeHelpService - file created successfully");
            }else {
                logger.info("HowToUseRiskOfficeHelpService - file already exists");
            }
            fw.write(helpPageContent); 
            fw.flush();
        }

        return "Sucessfully write into help page 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
}