用Java创建和写入(文本)文件的最简单方法是什么?
当前回答
如果出于某种原因想要将创建和编写行为分开,那么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()执行存在性检查,并自动创建文件。例如,如果您希望在写入文件之前确保自己是文件的创建者,这可能很有用。
其他回答
如果您希望获得相对轻松的体验,还可以查看Apache Commons IO包,更具体地说是FileUtils类。
永远不要忘记检查第三方库。用于日期操作的Joda Time、用于常见字符串操作的Apache Commons Lang StringUtils等可以使代码更可读。
Java是一种很棒的语言,但标准库有时有点低级。功能强大,但级别较低。
请注意,下面的每个代码示例都可能引发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);
我认为这是最短的路:
FileWriter fr = new FileWriter("your_file_name.txt"); // After '.' write
// your file extention (".txt" in this case)
fr.write("Things you want to write into the file"); // Warning: this will REPLACE your old file content!
fr.close();
以下是用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中读写文件的详细信息,请参阅本教程。
这里有一个创建或覆盖文件的小示例程序。这是一个长版本,因此可以更容易理解。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class writer {
public void writing() {
try {
//Whatever the file path is.
File statText = new File("E:/Java/Reference/bin/images/statsTest.txt");
FileOutputStream is = new FileOutputStream(statText);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("POTATO!!!");
w.close();
} catch (IOException e) {
System.err.println("Problem writing to the file statsTest.txt");
}
}
public static void main(String[]args) {
writer write = new writer();
write.writing();
}
}
推荐文章
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- 如何在Python中连接文本文件?
- “java”、“javaw”和“javaws”之间有什么区别?
- 将Date对象转换为日历对象