用Java创建和写入(文本)文件的最简单方法是什么?
当前回答
package fileoperations;
import java.io.File;
import java.io.IOException;
public class SimpleFile {
public static void main(String[] args) throws IOException {
File file =new File("text.txt");
file.createNewFile();
System.out.println("File is created");
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("Enter the text that you want to write");
writer.flush();
writer.close();
System.out.println("Data is entered into file");
}
}
其他回答
由于作者没有说明他们是否需要针对已经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("----------");
[...]
}
这些方法需要作者尽可能少的努力,并且在写入[文本]文件时应优先于其他所有方法。
如果您希望获得相对轻松的体验,还可以查看Apache Commons IO包,更具体地说是FileUtils类。
永远不要忘记检查第三方库。用于日期操作的Joda Time、用于常见字符串操作的Apache Commons Lang StringUtils等可以使代码更可读。
Java是一种很棒的语言,但标准库有时有点低级。功能强大,但级别较低。
使用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();
}
}
}
以下是用Java创建和编写文件的一些可能方法:
使用FileOutputStream
try {
File fout = new File("myOutFile.txt");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("Write somthing to the file ...");
bw.newLine();
bw.close();
} catch (FileNotFoundException e){
// File was not found
e.printStackTrace();
} catch (IOException e) {
// Problem when writing to the file
e.printStackTrace();
}
使用FileWriter
try {
FileWriter fw = new FileWriter("myOutFile.txt");
fw.write("Example of content");
fw.close();
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
} catch (IOException e) {
// Error when writing to the file
e.printStackTrace();
}
使用PrintWriter
try {
PrintWriter pw = new PrintWriter("myOutFile.txt");
pw.write("Example of content");
pw.close();
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
} catch (IOException e) {
// Error when writing to the file
e.printStackTrace();
}
使用OutputStreamWriter
try {
File fout = new File("myOutFile.txt");
FileOutputStream fos = new FileOutputStream(fout);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("Soe content ...");
osw.close();
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
} catch (IOException e) {
// Error when writing to the file
e.printStackTrace();
}
有关如何在Java中读写文件的详细信息,请参阅本教程。
如果您已经有了要写入文件的内容(而不是动态生成的),那么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();
}
推荐文章
- Javadoc @see或{@link}?
- 在准备语句中使用“like”通配符
- Android Eclipse -无法找到*.apk
- javac和Eclipse编译器之间的区别是什么?
- 工厂模式和策略模式之间的区别是什么?
- 在Java中使用正则表达式提取值
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址