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


#1楼

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

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

#2楼

采用:

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中引入的。


#3楼

如果您已经拥有要写入文件的内容(并且不是即时生成的),那么Java 7中作为本地I / O的java.nio.file.Files附加功能提供了最简单,最有效的方法你的目标。

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

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

#4楼

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

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

我们可以轻松地创建一个新文件并向其中添加内容。


#5楼

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

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
}

#6楼

采用:

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

#7楼

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

#8楼

我能找到的最简单方法:

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

它可能仅适用于1.7+。


#9楼

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

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

#10楼

仅一行! pathline是字符串

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

Files.write(Paths.get(path), lines.getBytes());

#11楼

我认为这是最短的方法:

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

#12楼

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

创建一个二进制文件:

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, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

创建一个二进制文件:

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

#13楼

在Java 7及更高版本中:

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

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

还要注意,您可以使用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)。


#14楼

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

#15楼

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

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

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


#16楼

如果您出于某种原因想要将创建和写入的行为分开,则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(); }

createNewFile()执行是否存在检查并自动创建文件。 例如,如果您想确保自己是文件的创建者,这将很有用。


#17楼

只需包括以下软件包:

java.nio.file

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

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

#18楼

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


首先,Java 6通常已经寿终正寝,并且由于作者没有指定他需要旧版兼容性,所以我想它会自动意味着Java 7或更高版本(Java 7尚未被IBM终止)。 因此,我们可以直接查看文件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("----------");
    [...]
}

这些方法所需的工作量很小,在写入[文本]文件时应优先于所有其他方法。


#19楼

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

#20楼

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

有几点要注意:

  1. 指定charset编码始终是一个好习惯,为此,我们在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();
}

#21楼

有一些简单的方法,例如:

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

#22楼

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

#23楼

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

#24楼

Java 7+值得一试:

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

看起来很有希望...


#25楼

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

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

#26楼

使用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文件。


#27楼

创建一个示例文件:

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

#28楼

以下是一些使用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中读取和写入文件的本教程。


#29楼

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

#30楼

最好的方法是使用Java7: Java 7引入了一种使用文件系统的新方法,以及一个新的实用程序类–文件。 使用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将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();
}

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