【问题标题】:How to create and output to files in Java如何在 Java 中创建和输出文件
【发布时间】:2019-06-07 16:10:56
【问题描述】:

我目前的问题在于,无论我尝试用什么解决方案在 Java 中创建文件,该文件永远不会被创建或显示。

我在 StackOverflow 上搜索了解决方案,并尝试了许多不同的代码,但都无济于事。我尝试过使用 BufferedWriter、PrintWriter、FileWriter,包裹在 try and catch 和 throwed IOExceptions 中,但似乎都不起作用。对于需要路径的每个字段,我都尝试了单独的文件名和路径中的文件名。没有任何效果。

//I've tried so much I don't know what to show. Here is what remains in my method: 

FileWriter fw = new FileWriter("testFile.txt", false);
PrintWriter output = new PrintWriter(fw);
fw.write("Hello");

每当我运行我过去的代码时,我都没有收到任何错误,但是,这些文件实际上从未出现过。我怎样才能解决这个问题? 提前谢谢!

【问题讨论】:

  • 你写完后关闭FileWriter了吗?
  • 1.添加fw.flush()fw.close()。 2. 您希望文件出现在哪里?为什么?
  • 是的!之后我确保关闭所有作者。
  • 您确定您在程序中拥有正确的current directory 吗?尝试给它一个绝对路径?

标签: java file java-io


【解决方案1】:

有几种方法可以做到这一点:

使用 BufferedWriter 写入:

public void writeWithBufferedWriter() 
  throws IOException {
    String str = "Hello";
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
    writer.write(str);

    writer.close();
}

如果要附加到文件:

public void appendUsingBufferedWritter() 
  throws IOException {
    String str = "World";
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
    writer.append(' ');
    writer.append(str);

    writer.close();
}

使用 PrintWriter:

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

使用 FileOutputStream:

public void usingFileOutputStream() 
  throws IOException {
    String str = "Hello";
    FileOutputStream outputStream = new FileOutputStream(fileName);
    byte[] strToBytes = str.getBytes();
    outputStream.write(strToBytes);

    outputStream.close();
}

注意:

  1. 如果您尝试写入不存在的文件,将首先创建该文件,并且不会引发异常。
  2. 使用后关闭流非常重要,因为它不会隐式关闭,以释放与其关联的任何资源。
  3. 在输出流中,close() 方法在释放资源之前调用 flush(),这会强制将任何缓冲的字节写入流。

来源和更多示例:https://www.baeldung.com/java-write-to-file

希望这会有所帮助。祝你好运。

【讨论】:

  • 确实做到了!非常感谢,我现在可以继续我的项目了。非常感谢。
【解决方案2】:

一些值得尝试的事情:

1) 如果您没有(它不在您显示的代码中),请确保在完成后关闭文件

2) 使用文件而不是字符串。这将让您仔细检查文件的创建位置

File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
FileWriter fw = new FileWriter(file, false);
fw.write("Hello");
fw.close();

作为奖励,Java 的 try-with-resource 会在完成后自动关闭资源,您可能想尝试一下

File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
try (FileWriter fw = new FileWriter(file, false)) {
    fw.write("Hello");
}

【讨论】:

    猜你喜欢
    • 2015-06-15
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 2018-07-25
    • 2019-02-20
    • 2011-03-02
    相关资源
    最近更新 更多