首页 文章

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

提问于
浏览
1204

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

30 回答

  • 1522

    Java 7值得一试:

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

    看起来很有希望......

  • 4

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

    基本上创建和写入文件只是一行,而且 one simple method call

    以下示例创建并写入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();
    }
    
  • 6

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

    //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");
            }
        }
    }
    
  • 6

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

    参考:File create Example in java

  • 119

    只有一行! pathline 是字符串

    import java.nio.file.Files;
    import java.nio.file.Paths;
    
    Files.write(Paths.get(path), lines.getBytes());
    
  • 40
    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();
            }
        }
    }
    
  • 6

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

    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
    }
    
  • 2

    使用:

    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);
    }
    
  • 9

    以下是使用Java创建和编写文件的一些可能方法:

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

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

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

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

    有关如何read and write files in Java的进一步检查本教程 .

  • 1

    如果由于某种原因想要分离创建和编写的行为,那么 touch 的Java等价物就是

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

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

  • 71

    只需包含此套餐:

    java.nio.file
    

    然后你可以使用这段代码来编写文件:

    Path file = ...;
    byte[] buf = ...;
    Files.write(file, buf);
    
  • 5

    使用JFilechooser阅读与客户的集合并保存到文件 .

    private void writeFile(){
    
        JFileChooser fileChooser = new JFileChooser(this.PATH);
        int retValue = fileChooser.showDialog(this, "Save File");
    
        if (retValue == JFileChooser.APPROVE_OPTION){
    
            try (Writer fileWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileChooser.getSelectedFile())))){
    
                this.customers.forEach((c) ->{
                    try{
                        fileWrite.append(c.toString()).append("\n");
                    }
                    catch (IOException ex){
                        ex.printStackTrace();
                    }
                });
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }
    }
    
  • 15

    创建示例文件:

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

    由于作者没有指定在指定它是 text (non-binary) 文件之前是否需要针对EoL _330329问题的Java版本的解决方案,因此我决定提供我的答案 .


    首先,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

    If you have all lines you will write (append) to the text file in advance ,推荐的方法是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);
    

    If you want to write file content as you gohttps://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("----------");
        [...]
    }
    

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

  • 32

    best way is to use Java7: Java 7引入了一种使用文件系统的新方法,以及一个新的实用程序类 - Files . 使用Files类,我们也可以创建,移动,复制,删除文件和目录;它也可以用来读写文件 .

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

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

    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

    现在让我们看看如何使用FileOutputStream将二进制数据写入文件 . 以下代码转换String int bytes并使用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 我们可以使用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();
    }
    

    Write with BufferedWriter: 使用BufferedWriter将String写入新文件:

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

    将String附加到现有文件:

    public void saveDataInFile(String data) throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
        writer.append(' ');
        writer.append(data);
    
        writer.close();
    }
    
  • 31
    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();
              }
            }
        }
    }
    
  • 18

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

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

    您甚至可以使用 system property 创建临时文件独立于您使用的操作系统 .

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

    我认为这是最短的方式:

    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();
    
  • 8

    使用Google的Guava库,我们可以非常轻松地创建和写入文件 .

    package com.zetcode.writetofileex;
    
    import com.google.common.io.Files;
    import java.io.File;
    import java.io.IOException;
    
    public class WriteToFileEx {
    
        public static void main(String[] args) throws IOException {
    
            String fileName = "fruits.txt";
            File file = new File(fileName);
    
            String content = "banana, orange, lemon, apple, plum";
    
            Files.write(content.getBytes(), file);
        }
    }
    

    该示例在项目根目录中创建一个新的 fruits.txt 文件 .

  • 7

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

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

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

  • 5

    我能找到最简单的方法:

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

    它可能只适用于1.7 .

  • 4

    如果我们使用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();
        }
    }
    

    有几点需要注意:

    • 指定charset编码总是一个好习惯,因为我们在类 StandardCharsets 中有常量 .

    • 该代码使用 try-with-resource 语句,其中资源在尝试后自动关闭 .

    虽然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();
    }
    
  • 4

    使用:

    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() 将自动关闭流 . 此版本简短,快速(缓冲)并允许选择编码 .

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

  • 4
    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");
        }
    }
    
  • 3

    在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
        }
    }
    
  • 3

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

    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
    

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

  • 2

    有一些简单的方法,如:

    File file = new File("filename.txt");
    PrintWriter pw = new PrintWriter(file);
    
    pw.write("The world I'm coming");
    pw.close();
    
    String write = "Hello World!";
    
    FileWriter fw = new FileWriter(file);
    BufferedWriter bw = new BufferedWriter(fw);
    
    fw.write(write);
    
    fw.close();
    
  • 0

    在Java 7及更高版本中:

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

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

    989 FileUtils.writeStringtoFile(..)来自commons-io
    来自 Guava

    另请注意,您可以使用 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*/}
    }
    

    另请参阅:Reading, Writing, and Creating Files(包括NIO2) .

  • 3

    请注意,下面的每个代码示例都可能抛出 IOException . 为简洁起见,省略了try / catch / finally块 . 有关异常处理的信息,请参阅this tutorial .

    创建一个文本文件(请注意,如果文件已经存在,这将覆盖该文件):

    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, Charset.forName("UTF-8"));
    //Files.write(file, lines, Charset.forName("UTF-8"), StandardOpenOption.APPEND);
    

    创建二进制文件:

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

相关问题