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


当前回答

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
}  

使用try()将自动关闭流。此版本短、快(缓冲),并支持选择编码。

这个特性是在Java7中引入的。

其他回答

要创建文件而不覆盖现有文件,请执行以下操作:

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
}

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

您甚至可以使用系统属性创建临时文件,该属性与您使用的操作系统无关。

File file = new File(System.*getProperty*("java.io.tmpdir") +
                     System.*getProperty*("file.separator") +
                     "YourFileName.txt");

创建示例文件:

try {
    File file = new File ("c:/new-file.txt");
    if(file.createNewFile()) {
        System.out.println("Successful created!");
    }
    else {
        System.out.println("Failed to create!");
    }
}
catch (IOException e) {
    e.printStackTrace();
}

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