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


当前回答

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {
    public static void main(String [] args) {
        FileWriter fw= null;
        File file =null;
        try {
            file=new File("WriteFile.txt");
            if(!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file);
            fw.write("This is an string written to a file");
            fw.flush();
            fw.close();
            System.out.println("File written Succesfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

其他回答

package fileoperations;
import java.io.File;
import java.io.IOException;

public class SimpleFile {
    public static void main(String[] args) throws IOException {
        File file =new File("text.txt");
        file.createNewFile();
        System.out.println("File is created");
        FileWriter writer = new FileWriter(file);

        // Writes the content to the file
        writer.write("Enter the text that you want to write"); 
        writer.flush();
        writer.close();
        System.out.println("Data is entered into file");
    }
}

如果您希望获得相对轻松的体验,还可以查看Apache Commons IO包,更具体地说是FileUtils类。

永远不要忘记检查第三方库。用于日期操作的Joda Time、用于常见字符串操作的Apache Commons Lang StringUtils等可以使代码更可读。

Java是一种很棒的语言,但标准库有时有点低级。功能强大,但级别较低。

以下是用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中读写文件的详细信息,请参阅本教程。

由于作者没有说明他们是否需要针对已经EoL的Java版本的解决方案(Sun和IBM都提供了,从技术上讲,这些版本是最广泛的JVM),并且由于大多数人似乎在作者的问题被指定为文本(非二进制)文件之前就已经回答了这个问题,所以我决定提供我的答案。


首先,Java 6通常已经到了生命的尽头,由于作者没有指定他需要遗留兼容性,我想这自动意味着Java 7或更高版本(Java 7尚未被IBM EoL)。因此,我们可以看看文件I/O教程:https://docs.oracle.com/javase/tutorial/essential/io/legacy.html

在Java SE 7发布之前,Java.io.File类是用于文件I/O的机制,但它有几个缺点。许多方法在失败时不会抛出异常,所以无法获得有用的错误消息。例如,如果文件删除失败,程序将收到“删除失败”,但不知道是否是因为文件不存在,用户不存在具有权限,或者存在其他问题。重命名方法跨平台工作不一致。没有真正的支持用于符号链接。需要对元数据提供更多支持,例如文件权限、文件所有者和其他安全属性。访问文件元数据效率低下。许多File方法都无法扩展。通过服务器请求大型目录列表可能会导致悬挂大目录还可能导致内存资源问题,导致拒绝服务。无法写入可以递归遍历文件树并做出响应的可靠代码如果存在循环符号链接,则可以适当。

哦,好吧,这排除了java.io.File。如果无法写入/附加文件,您可能甚至无法知道原因。


我们可以继续查看教程:https://docs.oracle.com/javase/tutorial/essential/io/file.html#common

如果您有所有要提前写入(附加)到文本文件的行,建议的方法是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-

下面是一个示例(简化):

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

另一个示例(附加):

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

如果您想按原样写入文件内容: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-

简化示例(Java 8或更高版本):

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

另一个示例(附加):

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

这些方法需要作者尽可能少的努力,并且在写入[文本]文件时应优先于其他所有方法。

这里有一个创建或覆盖文件的小示例程序。这是一个长版本,因此可以更容易理解。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class writer {
    public void writing() {
        try {
            //Whatever the file path is.
            File statText = new File("E:/Java/Reference/bin/images/statsTest.txt");
            FileOutputStream is = new FileOutputStream(statText);
            OutputStreamWriter osw = new OutputStreamWriter(is);    
            Writer w = new BufferedWriter(osw);
            w.write("POTATO!!!");
            w.close();
        } catch (IOException e) {
            System.err.println("Problem writing to the file statsTest.txt");
        }
    }

    public static void main(String[]args) {
        writer write = new writer();
        write.writing();
    }
}