用Java创建和写入(文本)文件的最简单方法是什么?
当前回答
Use:
JFileChooser c = new JFileChooser();
c.showOpenDialog(c);
File writeFile = c.getSelectedFile();
String content = "Input the data here to be written to your file";
try {
FileWriter fw = new FileWriter(writeFile);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(content);
bw.append("hiiiii");
bw.close();
fw.close();
}
catch (Exception exc) {
System.out.println(exc);
}
其他回答
请注意,下面的每个代码示例都可能引发IOException。为了简洁起见,省略了Try/catch/finally块。有关异常处理的信息,请参阅本教程。
请注意,如果文件已经存在,下面的每个代码示例都将覆盖该文件
创建文本文件:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
创建二进制文件:
byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();
Java 7+用户可以使用Files类写入文件:
创建文本文件:
List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
创建二进制文件:
byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
在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
}
}
Use:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) {
writer.write("text to write");
}
catch (IOException ex) {
// Handle me
}
使用try()将自动关闭流。此版本短、快(缓冲),并支持选择编码。
这个特性是在Java7中引入的。
如果您希望获得相对轻松的体验,还可以查看Apache Commons IO包,更具体地说是FileUtils类。
永远不要忘记检查第三方库。用于日期操作的Joda Time、用于常见字符串操作的Apache Commons Lang StringUtils等可以使代码更可读。
Java是一种很棒的语言,但标准库有时有点低级。功能强大,但级别较低。
这里我们将字符串输入到文本文件中:
String content = "This is the content to write into a file";
File file = new File("filename.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close(); // Be sure to close BufferedWriter
我们可以轻松地创建一个新文件并向其中添加内容。
推荐文章
- 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>"没有与主机名关联的地址