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


当前回答

Java 7+值得一试:

 Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());

看起来很有希望。。。

其他回答

如果我们使用的是Java7及以上版本,并且还知道要添加(附加)到文件中的内容,我们可以使用NIO包中的newBufferedWriter方法。

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

有几点需要注意:

指定字符集编码总是一个好习惯,因此我们在类StandardCharset中有常量。代码使用try with resource语句,其中资源在try之后自动关闭。

虽然OP没有询问,但为了以防万一我们想搜索具有特定关键字的行,例如机密,我们可以使用Java中的流API:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}

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

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

创建文本文件:

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

创建二进制文件:

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

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

创建文本文件:

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

创建二进制文件:

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

在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 static void writefromFile(ArrayList<String> lines, String destPath) {
        FileWriter fw;
        try {
            fw = new FileWriter(destPath);
            for (String str : lines) {
                fw.write(str);
            }
            fw.close();
         } catch (IOException ex) {
            JOptionPane.showMessageDialog("ERROR: exception was: " + ex.toString());
        }
        File f = new File(destPath);
        f.setExecutable(true);
    }

最好的方法是使用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();
}