【问题标题】:What is the simplest way to write a text file in Java?用Java编写文本文件的最简单方法是什么?
【发布时间】:2014-05-16 13:40:18
【问题描述】:

我想知道用 Java 编写文本文件的最简单(也是最简单)的方法是什么。请简单,因为我是初学者:D

我在网上搜索并找到了这段代码,但我理解了其中的 50%。

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

public class WriteToFileExample {
public static void main(String[] args) {
    try {

        String content = "This is the content to write into file";

        File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

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

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

【问题讨论】:

  • 我认为没有比这更简单的代码了。你能具体说明你不明白的地方吗?
  • 感谢您的回复!好吧,我不明白 FileWriter 和 BufferedWriter 类的作用。哦,最后是 carch(IOExeption) 部分。请你能简要解释一下你是做什么的。

标签: java file text


【解决方案1】:

追加文件FileWriter(String fileName, boolean append)

try {   // this is for monitoring runtime Exception within the block 

        String content = "This is the content to write into file"; // content to write into the file

        File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here

        // if file doesnt exists, then create it
        if (!file.exists()) {   // checks whether the file is Exist or not
            file.createNewFile();   // here if file not exist new file created 
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
        BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
        bw.write(content); // write method is used to write the given content into the file
        bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect. 

        System.out.println("Done");

    } catch (IOException e) { // if any exception occurs it will catch
        e.printStackTrace();
    }

【讨论】:

  • 感谢 cmets!现在画面更清晰了! :)
  • @BogGogo 查看更新的答案以附加文件内容而不删除以前的内容。 FileWriter 具有附加文件选项。该属性的默认值为 false。
【解决方案2】:

您可以使用来自 Apache Commons 的 FileUtils

import org.apache.commons.io.FileUtils;

final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);

【讨论】:

  • 如果有多行,可以使用.writeLines()。如果出现异常,它会为您正确关闭所有内容,并且System.getProperty 没有安全问题。所有这些东西都是没有共同点的痛苦。
【解决方案3】:

您可以使用JAVA 7 new File API 来做到这一点。

代码示例: `

public class FileWriter7 {
    public static void main(String[] args) throws IOException {
        List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
        String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
        writeSmallTextFile(lines, filepath);
    }

    private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
        Path path = Paths.get(aFileName);
        Files.write(path, aLines, StandardCharsets.UTF_8);
    }
}

`

【讨论】:

  • 请注意,这是迄今为止最简单的,因为您真正需要的是: Files.write(file.toPath(), content.getBytes());以满足原始问题的目标。
【解决方案4】:

您的代码是最简单的。但是,我总是尝试进一步优化代码。这是一个示例。

try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
    bw.write("Hello, This is a test message");
    bw.close();
    }catch (FileNotFoundException ex) {
    System.out.println(ex.toString());
    }

【讨论】:

  • 如果你这样做,我认为你的 FileWriter 不会被关闭。不知道这是否重要。
【解决方案5】:

Files.write() 正如@Dilip Kumar 所说的简单解决方案。我曾经使用这种方式,直到遇到问题,不能影响行分隔符(Unix/Windows)CR LF。

所以现在我使用 Java 8 流文件写入方式,这让我可以即时操作内容。 :)

List<String> lines = Arrays.asList(new String[] { "line1", "line2" });

Path path = Paths.get(fullFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {   
    writer.write(lines.stream()
                      .reduce((sum,currLine) ->  sum + "\n"  + currLine)
                      .get());
}     

通过这种方式,我可以指定行分隔符,或者我可以执行任何类型的魔法,例如 TRIM、大写、过滤等。

【讨论】:

    【解决方案6】:

    对于 Java 7 及更高版本,使用 Files 的单行:

    String text = "Text to save to file";
    Files.write(Paths.get("./fileName.txt"), text.getBytes());
    

    【讨论】:

    • 可能应该指定一个字符集。
    • @BradHards 我同意,但问题是最简单的方法,这就是 IMO 的简单程度。
    • 这会追加或覆盖指定的文件吗?
    • 后者@Peri461
    • 要附加到文件,我想你可以这样做Files.write(myPath, myString.getBytes(), StandardOpenOption.APPEND) 你也可以使用其他一些选项。
    【解决方案7】:
    File file = new File("path/file.name");
    IOUtils.write("content", new FileOutputStream(file));
    

    IOUtils 也可用于使用 java 8 轻松写入/读取文件。

    【讨论】:

      【解决方案8】:
      String content = "your content here";
      Path path = Paths.get("/data/output.txt");
      if(!Files.exists(path)){
          Files.createFile(path);
      }
      BufferedWriter writer = Files.newBufferedWriter(path);
      writer.write(content);
      

      【讨论】:

      【解决方案9】:

      Java 11或更高版本中,writeString可以从java.nio.file.Files使用,

      String content = "This is my content";
      String fileName = "myFile.txt";
      Files.writeString(Paths.get(fileName), content); 
      

      带选项:

      Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)
      

      有关java.nio.file.FilesStandardOpenOption 的更多文档

      【讨论】:

        猜你喜欢
        • 2011-12-06
        • 2010-09-23
        • 2023-03-07
        • 2014-01-28
        • 2021-04-13
        • 2023-03-17
        • 2019-06-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多