用Java创建和写入(文本)文件的最简单方法是什么?
当前回答
由于作者没有说明他们是否需要针对已经EoL的Java版本的解决方案(Sun和IBM都提供了,从技术上讲,这些版本是最广泛的JVM),并且由于大多数人似乎在作者的问题被指定为文本(非二进制)文件之前就已经回答了这个问题,所以我决定提供我的答案。
首先,Java 6通常已经到了生命的尽头,由于作者没有指定他需要遗留兼容性,我想这自动意味着Java 7或更高版本(Java 7尚未被IBM EoL)。因此,我们可以看看文件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("----------");
[...]
}
这些方法需要作者尽可能少的努力,并且在写入[文本]文件时应优先于其他所有方法。
其他回答
您甚至可以使用系统属性创建临时文件,该属性与您使用的操作系统无关。
File file = new File(System.*getProperty*("java.io.tmpdir") +
System.*getProperty*("file.separator") +
"YourFileName.txt");
用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);
}
}
}
如果您已经有了要写入文件的内容(而不是动态生成的),那么Java7中作为本机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();
}
使用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();
}
}
}
在Java8中,使用文件和路径,并使用trywithresources构造。
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
}
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap