用Java创建和写入(文本)文件的最简单方法是什么?
当前回答
有许多方法可以写入文件。每种方法都有其优点,而且在给定的场景中,每种方法可能都是最简单的。
这个答案以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的方法,好处是它不会吞下异常。
其他回答
我能找到的最简单的方法是:
Path sampleOutputPath = Paths.get("/tmp/testfile")
try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) {
writer.write("Hello, world!");
}
它可能只适用于1.7+。
用Java创建和写入文件的一种非常简单的方法:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class CreateFiles {
public static void main(String[] args) {
try{
// Create new file
String content = "This is the content to write into create file";
String path="D:\\a\\hi.txt";
File file = new File(path);
// If file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// Write in file
bw.write(content);
// Close connection
bw.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
要创建文件而不覆盖现有文件,请执行以下操作:
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.nio.file
然后,您可以使用以下代码编写文件:
Path file = ...;
byte[] buf = ...;
Files.write(file, buf);
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);
}
推荐文章
- 在流中使用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