用Java创建和写入(文本)文件的最简单方法是什么?
当前回答
创建示例文件:
try {
File file = new File ("c:/new-file.txt");
if(file.createNewFile()) {
System.out.println("Successful created!");
}
else {
System.out.println("Failed to create!");
}
}
catch (IOException e) {
e.printStackTrace();
}
其他回答
如果您已经有了要写入文件的内容(而不是动态生成的),那么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();
}
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");
}
}
如果我们使用的是Java7及以上版本,并且还知道要添加(附加)到文件中的内容,我们可以使用NIO包中的newBufferedWriter方法。
public static void main(String[] args) {
Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
String text = "\n Welcome to Java 8";
//Writing to the file temp.txt
try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
有几点需要注意:
指定字符集编码总是一个好习惯,因此我们在类StandardCharset中有常量。代码使用try with resource语句,其中资源在try之后自动关闭。
虽然OP没有询问,但为了以防万一我们想搜索具有特定关键字的行,例如机密,我们可以使用Java中的流API:
//Reading from the file the first line which contains word "confidential"
try {
Stream<String> lines = Files.lines(FILE_PATH);
Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
if(containsJava.isPresent()){
System.out.println(containsJava.get());
}
} catch (IOException e) {
e.printStackTrace();
}
要创建文件而不覆盖现有文件,请执行以下操作:
System.out.println("Choose folder to create file");
JFileChooser c = new JFileChooser();
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
c.showOpenDialog(c);
c.getSelectedFile();
f = c.getSelectedFile(); // File f - global variable
String newfile = f + "\\hi.doc";//.txt or .doc or .html
File file = new File(newfile);
try {
//System.out.println(f);
boolean flag = file.createNewFile();
if(flag == true) {
JOptionPane.showMessageDialog(rootPane, "File created successfully");
}
else {
JOptionPane.showMessageDialog(rootPane, "File already exists");
}
/* Or use exists() function as follows:
if(file.exists() == true) {
JOptionPane.showMessageDialog(rootPane, "File already exists");
}
else {
JOptionPane.showMessageDialog(rootPane, "File created successfully");
}
*/
}
catch(Exception e) {
// Any exception handling method of your choice
}
如果出于某种原因想要将创建和编写行为分开,那么Java中的touch等价物是
try {
//create a file named "testfile.txt" in the current working directory
File myFile = new File("testfile.txt");
if ( myFile.createNewFile() ) {
System.out.println("Success!");
} else {
System.out.println("Failure!");
}
} catch ( IOException ioe ) { ioe.printStackTrace(); }
createNewFile()执行存在性检查,并自动创建文件。例如,如果您希望在写入文件之前确保自己是文件的创建者,这可能很有用。
推荐文章
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- 如何在Python中连接文本文件?
- “java”、“javaw”和“javaws”之间有什么区别?
- 将Date对象转换为日历对象
- 在Java中保存最后N个元素的大小有限的队列