Java - 打开现有文件,如果不存在则使用 IO 流创建一个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1346821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:12:28  来源:igfitidea点击:

Java - open existing file or create one if doesn't exist using IO streams

javafile-iooverwrite

提问by Tony Stark

I was following instructions from a Java website (http://java.sun.com/docs/books/tutorial/essential/io/file.html#createStream) on creating or writing a file using an IO stream. However, the code it provides seems to be broken in multiple places:

我正在遵循 Java 网站 ( http://java.sun.com/docs/books/tutorial/essential/io/file.html#createStream) 中有关使用 IO 流创建或写入文件的说明。但是,它提供的代码似乎在多个地方被破坏:

import static java.nio.file.StandardOpenOption.*;

Path logfile = ...;

//Convert the string to a byte array.
String s = ...;
byte data[] = s.getBytes();

OutputStream out = null;
try {
    out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND));
    ...
    out.write(data, 0, data.length);
} catch (IOException x) {
    System.err.println(x);
} finally {
    if (out != null) {
        out.flush();
        out.close();
    }
}

For example, Eclipse crashes on the import, and on using the Path class, for starters. However, this tutorial seemed to provide exactly what I want to do - I want to write to a file if it exists (overwrite) or create a file if it doesn't exist, and ultimately I will be writing with an output stream (which gets created here using the .newOutputStream() method). So creating/writing with an output stream seemed like a likely candidate. Does anyone know how to either fix the above so that it works, or a better way to do what I want to do?

例如,Eclipse 在导入和使用 Path 类时崩溃,对于初学者来说。但是,本教程似乎准确地提供了我想要做的 - 如果文件存在(覆盖),我想写入文件,或者如果文件不存在则创建文件,最终我将使用输出流(它使用 .newOutputStream() 方法在此处创建)。因此,使用输出流创建/写入似乎是一个可能的候选者。有谁知道如何解决上述问题以使其正常工作,或者有更好的方法来做我想做的事情?

回答by Jesper

That example seems to be using APIs that are not part of Sun Java 6.

该示例似乎使用了不属于 Sun Java 6 的 API。

Class Pathand the package java.nio.fileare part of an API that is going to be added in Sun JDK 7. Note that the link to the documentation of Pathpoints to the API documentation of OpenJDK, Sun's open source development version of Java.

Path和包java.nio.file是将添加到 Sun JDK 7 中的 API 的一部分。请注意,指向文档的链接Path指向OpenJDK的 API 文档,OpenJDK是 Sun 的开源 Java 开发版本。

So, you cannot use those APIs if you are using regular Sun Java 6.

因此,如果您使用的是常规 Sun Java 6,则不能使用这些 API。

Read the warning on the start page of the tutorial:

阅读教程起始页上的警告:

File I/O (Featuring NIO.2)

This section is being updated to reflect features and conventions of the upcoming release, JDK7. You can download the current JDK7 Snapshot from java.net. We've published this preliminary version so you can get the most current information now, and so you can tell us about errors, omissions, or improvements we can make to this tutorial.

文件 I/O(具有 NIO.2)

本节正在更新以反映即将发布的 JDK7 的特性和约定。您可以从 java.net 下载当前的 JDK7 快照。我们已经发布了这个初步版本,以便您现在可以获得最新信息,并且您可以告诉我们关于本教程的错误、遗漏或改进。

In Sun Java 6 you can just use FileOutputStream. It will automatically create a new file if the file doesn't exist or overwrite an existing file if it exists:

在 Sun Java 6 中,您可以只使用FileOutputStream. 如果文件不存在,它将自动创建一个新文件,如果存在则覆盖现有文件:

FileOutputStream out = new FileOutputStream("filename.xyz");
out.write(data, 0, data.length);

Note: For writing text files (what is what you seem to want to do), use a Writer(for example FileWriter) instead of using an OutputStreamdirectly. The Writerwill take care of converting the text using a character encoding.

注意:对于编写文本文件(您似乎想要做什么),请使用 a Writer(例如FileWriter)而不是OutputStream直接使用 an 。在Writer将使用的字符编码转换文本的照顾。

See the Java SE 6 API Documentation(especially the docs of the packages java.io) for information about what's available in Java SE 6.

有关Java SE 6 中java.io可用内容的信息,请参阅Java SE 6 API 文档(尤其是包的文档)。