用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文件。

其他回答

在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)。

只有一行!路径和行是字符串

import java.nio.file.Files;
import java.nio.file.Paths;

Files.write(Paths.get(path), lines.getBytes());

我能找到的最简单的方法是:

Path sampleOutputPath = Paths.get("/tmp/testfile")
try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) {
    writer.write("Hello, world!");
}

它可能只适用于1.7+。

以下是用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中的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()执行存在性检查,并自动创建文件。例如,如果您希望在写入文件之前确保自己是文件的创建者,这可能很有用。