用Java创建和写入(文本)文件的最简单方法是什么?
当前回答
至少有几种方法可以创建文件并写入其中:
小文件(1.7)
您可以使用其中一种写入方法将字节或行写入文件。
Path file = Paths.get("path-to-file");
byte[] buf = "text-to-write-to-file".getBytes();
Files.write(file, buf);
这些方法为您处理大部分工作,例如打开和关闭流,但不适用于处理大型文件。
使用缓冲流I/O写入更大的文件(1.7)
java.nio.file包支持通道I/O,它可以在缓冲区中移动数据,绕过一些可能阻塞流I/O的层。
String s = "much-larger-text-to-write-to-file";
try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
writer.write(s, 0, s.length());
}
这种方法由于其高效的性能,特别是在完成大量写入操作时,是优先的。缓冲操作具有这种效果,因为它们不需要为每个字节调用操作系统的写入方法,从而减少了昂贵的I/O操作。
使用NIOAPI复制(并创建一个新的)带有输出流的文件(1.7)
Path oldFile = Paths.get("existing-file-path");
Path newFile = Paths.get("new-file-path");
try (OutputStream os = new FileOutputStream(newFile.toFile())) {
Files.copy(oldFile, os);
}
还有其他方法允许将输入流中的所有字节复制到文件中。
FileWriter(文本)(<1.7)
直接写入文件(性能较低),仅当写入次数较少时才应使用。用于将面向字符的数据写入文件。
String s= "some-text";
FileWriter fileWriter = new FileWriter("C:\\path\\to\\file\\file.txt");
fileWriter.write(fileContent);
fileWriter.close();
FileOutputStream(二进制)(<1.7)
FileOutputStream用于写入原始字节流,如图像数据。
byte data[] = "binary-to-write-to-file".getBytes();
FileOutputStream out = new FileOutputStream("file-name");
out.write(data);
out.close();
使用这种方法,应该考虑始终写入字节数组,而不是一次写入一个字节。加速可能非常显著-高达10倍或更高。因此,建议尽可能使用write(byte[])方法。
其他回答
至少有几种方法可以创建文件并写入其中:
小文件(1.7)
您可以使用其中一种写入方法将字节或行写入文件。
Path file = Paths.get("path-to-file");
byte[] buf = "text-to-write-to-file".getBytes();
Files.write(file, buf);
这些方法为您处理大部分工作,例如打开和关闭流,但不适用于处理大型文件。
使用缓冲流I/O写入更大的文件(1.7)
java.nio.file包支持通道I/O,它可以在缓冲区中移动数据,绕过一些可能阻塞流I/O的层。
String s = "much-larger-text-to-write-to-file";
try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
writer.write(s, 0, s.length());
}
这种方法由于其高效的性能,特别是在完成大量写入操作时,是优先的。缓冲操作具有这种效果,因为它们不需要为每个字节调用操作系统的写入方法,从而减少了昂贵的I/O操作。
使用NIOAPI复制(并创建一个新的)带有输出流的文件(1.7)
Path oldFile = Paths.get("existing-file-path");
Path newFile = Paths.get("new-file-path");
try (OutputStream os = new FileOutputStream(newFile.toFile())) {
Files.copy(oldFile, os);
}
还有其他方法允许将输入流中的所有字节复制到文件中。
FileWriter(文本)(<1.7)
直接写入文件(性能较低),仅当写入次数较少时才应使用。用于将面向字符的数据写入文件。
String s= "some-text";
FileWriter fileWriter = new FileWriter("C:\\path\\to\\file\\file.txt");
fileWriter.write(fileContent);
fileWriter.close();
FileOutputStream(二进制)(<1.7)
FileOutputStream用于写入原始字节流,如图像数据。
byte data[] = "binary-to-write-to-file".getBytes();
FileOutputStream out = new FileOutputStream("file-name");
out.write(data);
out.close();
使用这种方法,应该考虑始终写入字节数组,而不是一次写入一个字节。加速可能非常显著-高达10倍或更高。因此,建议尽可能使用write(byte[])方法。
如果我们使用的是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();
}
如果出于某种原因想要将创建和编写行为分开,那么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()执行存在性检查,并自动创建文件。例如,如果您希望在写入文件之前确保自己是文件的创建者,这可能很有用。
public class Program {
public static void main(String[] args) {
String text = "Hello world";
BufferedWriter output = null;
try {
File file = new File("example.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
try {
output.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
}
以下是编写文件的代码,也在退出帮助内容网页时删除:
public String writeHelpContent(String filePath, String helpPageContent) throws IOException{
logger.info("HowToUseRiskOfficeHelpService - writeHelpContent start");
File file = new File(filePath);
try(FileWriter fw = new FileWriter(file);){
file.deleteOnExit();
if(file.createNewFile()) {
logger.info("HowToUseRiskOfficeHelpService - file created successfully");
}else {
logger.info("HowToUseRiskOfficeHelpService - file already exists");
}
fw.write(helpPageContent);
fw.flush();
}
return "Sucessfully write into help page file";
}
推荐文章
- 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>"没有与主机名关联的地址