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

2018-12-30 23:30发布

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

标签: java file-io
30条回答
永恒的永恒
2楼-- · 2018-12-31 00:06

In Java 7 and up:

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 can use a FileWriter, but it uses the default encoding, which is often a bad idea - it's best to specify the encoding explicitly.

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


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

查看更多
几人难应
3楼-- · 2018-12-31 00:06

Since the author did not specify whether they require a solution for Java versions that have been EoL'd (by both Sun and IBM, and these are technically the most widespread JVMs), and due to the fact that most people seem to have answered the author's question before it was specified that it is a text (non-binary) file, I have decided to provide my answer.


First of all, Java 6 has generally reached end of life, and since the author did not specify he needs legacy compatibility, I guess it automatically means Java 7 or above (Java 7 is not yet EoL'd by IBM). So, we can look right at the file I/O tutorial: https://docs.oracle.com/javase/tutorial/essential/io/legacy.html

Prior to the Java SE 7 release, the java.io.File class was the mechanism used for file I/O, but it had several drawbacks.

  • Many methods didn't throw exceptions when they failed, so it was impossible to obtain a useful error message. For example, if a file deletion failed, the program would receive a "delete fail" but wouldn't know if it was because the file didn't exist, the user didn't have permissions, or there was some other problem.
  • The rename method didn't work consistently across platforms.
  • There was no real support for symbolic links.
  • More support for metadata was desired, such as file permissions, file owner, and other security attributes. Accessing file metadata was inefficient.
  • Many of the File methods didn't scale. Requesting a large directory listing over a server could result in a hang. Large directories could also cause memory resource problems, resulting in a denial of service.
  • It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links.

Oh well, that rules out java.io.File. If a file cannot be written/appended, you may not be able to even know why.


We can continue looking at the tutorial: https://docs.oracle.com/javase/tutorial/essential/io/file.html#common

If you have all lines you will write (append) to the text file in advance, the recommended approach is https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio.file.OpenOption...-

Here's an example (simplified):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, StandardCharsets.UTF_8);

Another example (append):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE);

If you want to write file content as you go: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedWriter-java.nio.file.Path-java.nio.charset.Charset-java.nio.file.OpenOption...-

Simplified example (Java 8 or up):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file)) {
    writer.append("Zero header: ").append('0').write("\r\n");
    [...]
}

Another example (append):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
    writer.write("----------");
    [...]
}

These methods require minimal effort on the author's part and should be preferred to all others when writing to [text] files.

查看更多
旧人旧事旧时光
4楼-- · 2018-12-31 00:07

best way is to use Java7: Java 7 introduces a new way of working with the filesystem, along with a new utility class – Files. Using the Files class, we can create, move, copy, delete files and directories as well; it also can be used to read and write to a file.

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

    Files.write(path, strToBytes);
}

Write with FileChannel If you are dealing with large files, FileChannel can be faster than standard IO. The following code write String to a file using 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();
}

Write with 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();
}

Write with FileOutputStream

Let’s now see how we can use FileOutputStream to write binary data to a file. The following code converts a String int bytes and writes the bytes to file using a FileOutputStream:

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

    outputStream.close();
}

Write with PrintWriter we can use a PrintWriter to write formatted text to a file:

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

Write with BufferedWriter: use BufferedWriter to write a String to a new file:

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

    writer.close();
}

append a String to the existing file:

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

    writer.close();
}
查看更多
骚的不知所云
5楼-- · 2018-12-31 00:08

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.

This feature was introduced in Java 7.

查看更多
不流泪的眼
6楼-- · 2018-12-31 00:08

Just include this package:

java.nio.file

And then you can use this code to write the file:

Path file = ...;
byte[] buf = ...;
Files.write(file, buf);
查看更多
余生请多指教
7楼-- · 2018-12-31 00:09

One line only ! path and line are Strings

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

Files.write(Paths.get(path), lines.getBytes());
查看更多
登录 后发表回答