用Java创建和写入(文本)文件的最简单方法是什么?
当前回答
如果我们使用的是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();
}
其他回答
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterExample {
public static void main(String [] args) {
FileWriter fw= null;
File file =null;
try {
file=new File("WriteFile.txt");
if(!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file);
fw.write("This is an string written to a file");
fw.flush();
fw.close();
System.out.println("File written Succesfully");
} catch (IOException e) {
e.printStackTrace();
}
}
}
这里有一个创建或覆盖文件的小示例程序。这是一个长版本,因此可以更容易理解。
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();
}
}
以下是编写文件的代码,也在退出帮助内容网页时删除:
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";
}
请注意,下面的每个代码示例都可能引发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);
有许多方法可以写入文件。每种方法都有其优点,而且在给定的场景中,每种方法可能都是最简单的。
这个答案以Java 8为中心,并试图涵盖Java专业考试所需的所有细节。涉及的课程包括:
.
├── OutputStream
│ └── FileOutputStream
├── Writer
│ ├── OutputStreamWriter
│ │ └── FileWriter
│ ├── BufferedWriter
│ └── PrintWriter (Java 5+)
└── Files (Java 7+)
写入文件有5种主要方式:
┌───────────────────────────┬────────────────────────┬─────────────┬──────────────┐
│ │ Buffer for │ Can specify │ Throws │
│ │ large files? │ encoding? │ IOException? │
├───────────────────────────┼────────────────────────┼─────────────┼──────────────┤
│ OutputStreamWriter │ Wrap in BufferedWriter │ Y │ Y │
│ FileWriter │ Wrap in BufferedWriter │ │ Y │
│ PrintWriter │ Y │ Y │ │
│ Files.write() │ │ Y │ Y │
│ Files.newBufferedWriter() │ Y │ Y │ Y │
└───────────────────────────┴────────────────────────┴─────────────┴──────────────┘
每个都有其独特的优势:
OutputStreamWriter-Java 5之前最基本的方法FileWriter–可选附加构造函数参数PrintWriter–多种方法Files.write()–在一次调用中创建并写入文件Files.newBufferedWriter()–便于编写大型文件
以下是每一项的详细信息。
文件输出流
此类用于写入原始字节流。下面的所有Writer方法都依赖于这个类,无论是显式的还是隐藏式的。
try (FileOutputStream stream = new FileOutputStream("file.txt");) {
byte data[] = "foo".getBytes();
stream.write(data);
} catch (IOException e) {}
注意,trywithresources语句负责stream.close(),关闭流会刷新它,就像stream.flush()一样。
输出StreamWriter
此类是从字符流到字节流的桥梁。它可以包装FileOutputStream,并写入字符串:
Charset utf8 = StandardCharsets.UTF_8;
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File("file.txt")), utf8)) {
writer.write("foo");
} catch (IOException e) {}
缓冲写入程序
此类将文本写入字符输出流,缓冲字符,以便有效地写入单个字符、数组和字符串。
它可以包装OutputStreamWriter:
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("file.txt"))))) {
writer.write("foo");
writer.newLine(); // method provided by BufferedWriter
} catch (IOException e) {}
在Java5之前,这是处理大型文件的最佳方法(具有常规的try/catch块)。
字符输出流
这是OutputStreamWriter的子类,是编写字符文件的便利类:
boolean append = false;
try(FileWriter writer = new FileWriter("file.txt", append) ){
writer.write("foo");
writer.append("bar");
} catch (IOException e) {}
关键的好处是它有一个可选的附加构造函数参数,该参数决定它是附加到现有文件还是覆盖现有文件。注意,append/overwrite行为不受write()和append()方法的控制,它们的行为方式几乎相同。
注意:
没有缓冲,但为了处理大型文件,可以将其包装在BufferedWriter中。FileWriter使用默认编码。通常最好明确指定编码
字符打印流
此类将对象的格式化表示打印到文本输出流。实际上,它与上面的BufferedWriter方法(新的BufferedWriter(新的OutputStreamWriter(新的FileOutputStream(…)))相同。PrintWriter是在Java5中引入的,作为调用此习惯用法的方便方法,并添加了printf()和println()等其他方法。
此类中的方法不会引发I/O异常。您可以通过调用checkError()来检查错误。PrintWriter实例的目标可以是File、OutputStream或Writer。以下是写入文件的示例:
try (PrintWriter writer = new PrintWriter("file.txt", "UTF-8")) {
writer.print("foo");
writer.printf("bar %d $", "a", 1);
writer.println("baz");
} catch (FileNotFoundException e) {
} catch (UnsupportedEncodingException e) {}
当写入OutputStream或Writer时,有一个可选的autoFlush构造函数参数,默认为false。与FileWriter不同,它将覆盖任何现有文件。
文件.write()
Java7引入了Java.nio.file.Files.Files.write(),它允许您在一次调用中创建和写入文件。
@icza的答案显示了如何使用这种方法。几个例子:
Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("foo", "bar");
try {
Files.write(Paths.get("file.txt"), "foo".getBytes(utf8));
Files.write(Paths.get("file2.txt"), lines, utf8);
} catch (IOException e) {}
这不涉及缓冲区,因此不适用于大型文件。
文件.newBufferedWriter()
Java 7还引入了Files.newBufferedWriter(),这使得获取BufferedWriter变得容易:
Charset utf8 = StandardCharsets.UTF_8;
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("file.txt"), utf8)) {
writer.write("foo");
} catch (IOException e) {}
这与PrintWriter类似,缺点是没有PrintWriter的方法,好处是它不会吞下异常。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap