我当前的问题在于,无论我尝试使用什么解决方案在 Java 中创建文件,该文件都永远不会被创建或显示。
我在 StackOverflow 上搜索了解决方案,并尝试了很多很多不同的代码,但都无济于事。我尝试过使用 BufferedWriter、PrintWriter、FileWriter,包装在 try 和 catch 中并抛出 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");
每当我运行过去的代码时,我都不会抛出任何错误,但是,这些文件从未真正显示出来。我怎样才能解决这个问题? 预先感谢您!
最佳答案
有几种方法可以做到这一点:
使用 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();
}
使用文件输出流:
public void usingFileOutputStream()
throws IOException {
String str = "Hello";
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = str.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
注意:
- 如果您尝试写入不存在的文件,系统会先创建该文件,并且不会引发异常。
- 使用流后关闭流非常重要,因为它不会隐式关闭,以释放与其关联的任何资源。
- 在输出流中,close() 方法在释放资源之前调用flush(),这会强制将任何缓冲的字节写入流。
来源和更多示例:https://www.baeldung.com/java-write-to-file
希望这有帮助。祝你好运。
关于java - 如何在 Java 中创建文件并输出到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56497942/