如何创建文件并用Java写入?

Dre*_*son 1336 java file-io

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

Mic*_*ael 1684

请注意,下面的每个代码示例都可能抛出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();
Run Code Online (Sandbox Code Playgroud)

创建二进制文件:

byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

创建二进制文件:

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

  • 值得注意的是,如果文件已经存在,PrintWriter会将文件大小截断为零 (55认同)
  • PrintWriter可以(通常是)使用,但不是(概念上)正确的工作类.从文档:`"PrintWriter打印对象的格式化表示到文本输出流."Bozho的答案更正确,虽然它看起来很麻烦(你总是可以用一些实用方法包装它). (34认同)
  • 因此,在构建应用程序并在另一台PC中使用后,将在何处创建文本文件,因为我们没有给出路径? (14认同)
  • @MarlonAbeykoon好问题.答案是它将在*工作目录*中创建文本文件.工作目录是您执行程序的任何目录.例如,如果从命令行执行程序,则工作目录将是您当时"进入"的任何目录(在Linux上,键入"pwd"以查看当前工作目录).或者,如果我双击桌面上的JAR文件来运行它,那么工作目录将是桌面. (13认同)
  • `writer.close()`应该在finally块中 (8认同)

Boz*_*zho 404

在Java 7及更高版本中:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(
              new FileOutputStream("filename.txt"), "utf-8"))) {
   writer.write("something");
}
Run Code Online (Sandbox Code Playgroud)

但是有一些有用的实用程序:

另请注意,您可以使用a 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*/}
}
Run Code Online (Sandbox Code Playgroud)

另请参阅:读取,写入和创建文件(包括NIO2).

  • 看起来像writer没有writeln()方法.它只有write() (14认同)
  • 如果将编写器的类型更改为BufferedWriter(实际上是),则可以使用writer.newLine() (10认同)
  • @leonbloy我知道这是一个陈旧的评论,但如果有人看到这个,你会介意解释为什么不"永远有益"?至少在这里它说"顶级高效"http://docs.oracle.com/javase/1.5.0/docs/api/java/io/OutputStreamWriter.html (5认同)
  • 在finally中有一个try/catch似乎是不对的.我知道原因,但它似乎是一种代码味道. (4认同)
  • @Trengot确实如此.在包围任何其他流的任何流上调用`close()`也将关闭所有内部流. (3认同)

icz*_*cza 127

如果您已经拥有要写入文件的内容(而不是动态生成),则java.nio.file.FilesJava 7中作为本机I/O的一部分添加提供了实现目标的最简单,最有效的方法.

基本上创建和写入文件只是一行,而且一个简单的方法调用!

以下示例创建并写入6个不同的文件以展示如何使用它:

Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("1st line", "2nd line");
byte[] data = {1, 2, 3, 4, 5};

try {
    Files.write(Paths.get("file1.bin"), data);
    Files.write(Paths.get("file2.bin"), data,
            StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    Files.write(Paths.get("file3.txt"), "content".getBytes());
    Files.write(Paths.get("file4.txt"), "content".getBytes(utf8));
    Files.write(Paths.get("file5.txt"), lines, utf8);
    Files.write(Paths.get("file6.txt"), lines, utf8,
            StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*lje 72

public class Program {
    public static void main(String[] args) {
        String text = "Hello world";
        BufferedWriter output = null;
        try {
            File file = new File("example.txt");
            output = new BufferedWriter(new FileWriter(file));
            output.write(text);
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
          if ( output != null ) {
            output.close();
          }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 将output.close()放在finally块中会不会更好? (18认同)
  • 单纯的代码永远不会构成答案.你必须解释一下. (7认同)
  • 实际上这不会编译,`output.close()`抛出IOException (7认同)

小智 41

这是一个用于创建或覆盖文件的示例程序.它是长版本,因此可以更容易理解.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Anu*_*man 36

在Java中创建和写入文件的一种非常简单的方法:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class CreateFiles {

    public static void main(String[] args) {
        try{
            // Create new file
            String content = "This is the content to write into create file";
            String path="D:\\a\\hi.txt";
            File file = new File(path);

            // If file doesn't exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);

            // Write in file
            bw.write(content);

            // Close connection
            bw.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

参考:文件在java中创建示例

  • 这里的`File.exists()/ createNewFile()`代码既没有意义又浪费.创建`new FileWriter()`时,操作系统必须做同样的事情.你强迫它发生两次. (6认同)
  • 我使用了这种方法,但你必须知道它每次都会覆盖文件.如果你希望它附加以防文件存在,你必须按如下方式实例化`FileWriter`:`new FileWriter(file.getAbsoluteFile(),true)` (2认同)
  • 由于我所说的原因,这既*没有意义*又*浪费。您正在导致*两个*存在测试,*两个*创建,*和*删除:并且*您在此*不*执行不同的代码,具体取决于文件是否已存在。 (2认同)

icl*_*126 33

使用:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) {
    writer.write("text to write");
} 
catch (IOException ex) {
    // Handle me
}  
Run Code Online (Sandbox Code Playgroud)

使用try()将自动关闭流.此版本简短,快速(缓冲)并允许选择编码.

此功能是在Java 7中引入的.

  • 应该注意这是Java 7的一个特性,因此在以前的Java版本中不起作用. (5认同)
  • 可以使用"常量"`StandardCharsets.UTF_8`而不是"utf-8"字符串(这可以防止输入错误)`... new OutputStreamWriter(new FileOutputStream("myFile.txt"),StandardCharsets.UTF_8). ..` - java.nio.charset.StandardCharsets`是在java 7中引入的 (3认同)

iKi*_*ing 19

这里我们在一个文本文件中输入一个字符串:

String content = "This is the content to write into a file";
File file = new File("filename.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close(); // Be sure to close BufferedWriter
Run Code Online (Sandbox Code Playgroud)

我们可以轻松创建新文件并在其中添加内容.


ext*_*eon 15

如果您希望获得相对无痛苦的体验,您还可以查看Apache Commons IO软件包,更具体地说是FileUtils该类.

永远不要忘记检查第三方库.Joda-日期操作的时间,Apache Commons LangStringUtils用于常见的字符串操作等可以使您的代码更具可读性.

Java是一种很棒的语言,但标准库有时候有点低级.虽然功能强大,但却很低级.


afk*_*min 15

由于作者没有说明他们是否需要一个已经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#写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);
Run Code Online (Sandbox Code Playgroud)

另一个例子(追加):

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

如果您想要编写文件内容: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");
    [...]
}
Run Code Online (Sandbox Code Playgroud)

另一个例子(追加):

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

这些方法对作者来说需要的工作量很小,在写入[text]文件时应该优先于所有其他方法.


Mar*_*ers 10

如果由于某种原因想要分离创建和写入的行为,则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(); }
Run Code Online (Sandbox Code Playgroud)

createNewFile()存在检查和文件创建原子.例如,如果您想在写入文件之前确保自己是文件的创建者,这将非常有用.


Meh*_*hdi 10

以下是使用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();
}
Run Code Online (Sandbox Code Playgroud)

使用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();
}
Run Code Online (Sandbox Code Playgroud)

使用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();
}
Run Code Online (Sandbox Code Playgroud)

使用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();
}
Run Code Online (Sandbox Code Playgroud)

有关如何使用Java读取和写入文件的详细信息,请参阅本教程.


小智 9

使用:

JFileChooser c = new JFileChooser();
c.showOpenDialog(c);
File writeFile = c.getSelectedFile();
String content = "Input the data here to be written to your file";

try {
    FileWriter fw = new FileWriter(writeFile);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(content);
    bw.append("hiiiii");
    bw.close();
    fw.close();
}
catch (Exception exc) {
   System.out.println(exc);
}
Run Code Online (Sandbox Code Playgroud)


saj*_*asi 9

最好的方法是使用Java7: Java 7引入了一种使用文件系统的新方法,以及一个新的实用程序类–文件。使用Files类,我们还可以创建,移动,复制,删除文件和目录。它还可以用于读取和写入文件。

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

    Files.write(path, strToBytes);
}
Run Code Online (Sandbox Code Playgroud)

使用FileChannel写入 如果要处理大文件,FileChannel可能比标准IO更快。以下代码使用FileChannel将String写入文件:

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();
}
Run Code Online (Sandbox Code Playgroud)

用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();
}
Run Code Online (Sandbox Code Playgroud)

用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();
}
Run Code Online (Sandbox Code Playgroud)

写有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();
}
Run Code Online (Sandbox Code Playgroud)

使用BufferedWriter写入使用BufferedWriter将字符串写入新文件:

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

    writer.close();
}
Run Code Online (Sandbox Code Playgroud)

将字符串追加到现有文件:

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

    writer.close();
}
Run Code Online (Sandbox Code Playgroud)


ben*_*ben 8

我认为这是最短的方式:

FileWriter fr = new FileWriter("your_file_name.txt"); // After '.' write
// your file extention (".txt" in this case)
fr.write("Things you want to write into the file"); // Warning: this will REPLACE your old file content!
fr.close();
Run Code Online (Sandbox Code Playgroud)


aas*_*ima 7

要创建文件而不覆盖现有文件:

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
}
Run Code Online (Sandbox Code Playgroud)


小智 6

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

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");
    }
}
Run Code Online (Sandbox Code Playgroud)


pra*_*ver 6

在 Java 8 中使用文件和路径并使用 try-with-resources 构造。

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WriteFile{
    public static void main(String[] args) throws IOException {
        String file = "text.txt";
        System.out.println("Writing to file: " + file);
        // Files.newBufferedWriter() uses UTF-8 encoding by default
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(file))) {
            writer.write("Java\n");
            writer.write("Python\n");
            writer.write("Clojure\n");
            writer.write("Scala\n");
            writer.write("JavaScript\n");
        } // the file will be automatically closed
    }
}
Run Code Online (Sandbox Code Playgroud)


qed*_*qed 5

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

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

它可能只适用于1.7+.


小智 5

使用输入和输出流读写文件:

//Coded By Anurag Goel
//Reading And Writing Files
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class WriteAFile {
    public static void main(String args[]) {
        try {
            byte array [] = {'1','a','2','b','5'};
            OutputStream os = new FileOutputStream("test.txt");
            for(int x=0; x < array.length ; x++) {
                os.write( array[x] ); // Writes the bytes
            }
            os.close();

            InputStream is = new FileInputStream("test.txt");
            int size = is.available();

            for(int i=0; i< size; i++) {
                System.out.print((char)is.read() + " ");
            }
            is.close();
        } catch(IOException e) {
            System.out.print("Exception");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ran*_*ler 5

只有一行! path并且line是字符串

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

Files.write(Paths.get(path), lines.getBytes());
Run Code Online (Sandbox Code Playgroud)


小智 5

只包括这个包:

java.nio.file
Run Code Online (Sandbox Code Playgroud)

然后您可以使用此代码编写文件:

Path file = ...;
byte[] buf = ...;
Files.write(file, buf);
Run Code Online (Sandbox Code Playgroud)


i_a*_*ero 5

如果我们使用 Java 7 及更高版本并且还知道要添加(追加)到文件的内容,我们可以使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

有几点需要注意:

  1. 指定字符集编码始终是一个好习惯,为此我们在 class 中有常量StandardCharsets
  2. 代码try-with-resource中使用了try后自动关闭资源的语句。

虽然OP没有询问,但以防万一我们想要搜索具有某些特定关键字的行,例如confidential我们可以使用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();
}
Run Code Online (Sandbox Code Playgroud)


Olu*_*ith 5

Java 7+值得一试:

 Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());
Run Code Online (Sandbox Code Playgroud)

看起来很有希望...


Der*_*ill 5

此答案以 Java 8 为中心,并试图涵盖Java 专业考试所需的所有详细信息。它试图解释为什么存在不同的方法。它们各有各的好处,而且在给定的场景中,每个都可能是最简单的。

涉及的类包括:

.
??? OutputStream
?   ??? FileOutputStream
??? Writer
?   ??? OutputStreamWriter
?   ?   ??? FileWriter
?   ??? BufferedWriter
?   ??? PrintWriter (Java 5+)
??? Files (Java 7+)
Run Code Online (Sandbox Code Playgroud)

文件输出流

此类用于写入原始字节流。Writer下面的所有方法都依赖于这个类,无论是显式的还是隐藏的

.
??? OutputStream
?   ??? FileOutputStream
??? Writer
?   ??? OutputStreamWriter
?   ?   ??? FileWriter
?   ??? BufferedWriter
?   ??? PrintWriter (Java 5+)
??? Files (Java 7+)
Run Code Online (Sandbox Code Playgroud)

请注意,try-with-resources 语句负责处理stream.close()并且关闭流会刷新它,就像stream.flush()(下面的所有示例都使用这种方法)。

输出流写入器

这个类是从字符流到字节流的桥梁。它可以包装 a FileOutputStream,并写入字符串:

try (FileOutputStream stream = new FileOutputStream("file.txt");) {
    byte data[] = "foo".getBytes();
    stream.write(data);
} catch (IOException e) {}
Run Code Online (Sandbox Code Playgroud)

缓冲写入器

此类将文本写入字符输出流,缓冲字符以提供单个字符、数组和字符串的高效写入。

它可以包装一个OutputStreamWriter

Charset utf8 = StandardCharsets.UTF_8;
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File("file.txt")), utf8)) {
    writer.write("foo");
} catch (IOException e) {}
Run Code Online (Sandbox Code Playgroud)

在 Java 5 之前,这是处理大文件的最佳方法(带有常规的 try/catch 块)。

文件写入器

这是 , 的子类OutputStreamWriter,是编写字符文件的便利类:

try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("file.txt"))))) {
    writer.write("foo");
    writer.newLine();  // method provided by BufferedWriter
} catch (IOException e) {}
Run Code Online (Sandbox Code Playgroud)

关键的好处是它有一个可选的append构造函数参数,它决定了它是附加到还是覆盖现有文件。请注意,追加/覆盖行为不受write()append()方法的控制,它们的行为方式几乎相同

注意:

  • 没有缓冲,但为了处理大文件,它可以包装在BufferedWriter.
  • FileWriter使用默认编码。通常最好明确指定编码

打印写入器

此类将对象的格式化表示打印到文本输出流。实际上,它与BufferedWriter上面的方法 ( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(...)))) 相同。PrintWriter在 Java 5 中引入作为调用此习语的便捷方式,并添加了其他方法,例如printf()println()

此类中的方法不会引发 I/O 异常。您可以通过调用来检查错误checkError()。PrintWriter 实例的目标可以是 File、OutputStream 或 Writer。以下是写入文件的示例:

boolean append = false;
try(FileWriter writer = new FileWriter("file.txt", append) ){
    writer.write("foo");
    writer.append("bar");
} catch (IOException e) {}
Run Code Online (Sandbox Code Playgroud)

写入OutputStreamor 时Writer有一个可选的autoFlush构造函数参数,默认情况下为 false。与 不同FileWriter,它将覆盖任何现有文件。

文件.write()

Java 7 引入了java.nio.file.Files. Files.write()允许您在一次调用中创建和写入文件。

@icza 的回答显示了如何使用此方法。几个例子:

try (PrintWriter writer = new PrintWriter("file.txt", "UTF-8")) {
    writer.print("foo");
    writer.printf("bar %d $", "a", 1);
    writer.println("baz");
} catch (FileNotFoundException e) {
} catch (UnsupportedEncodingException e) {}
Run Code Online (Sandbox Code Playgroud)

这不涉及缓冲区,因此不适合大文件。

Files.newBufferedWriter()

Java 7 还引入了Files.newBufferedWriter()这使得很容易获得BufferedWriter

Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("foo", "bar");

try {
    Files.write(Paths.get("file.txt"), "foo".getBytes(utf8));
    Files.write(Paths.get("file2.txt"), lines, utf8);
} catch (IOException e) {}
Run Code Online (Sandbox Code Playgroud)

这类似于PrintWriter,但缺点是没有 PrintWriter 的方法,并且好处是它不会吞下异常

概括

Charset utf8 = StandardCharsets.UTF_8;
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("file.txt"), utf8)) {
    writer.write("foo");
} catch (IOException e) {}
Run Code Online (Sandbox Code Playgroud)