如何写入文件?(How to write to a file?)
优质
小牛编辑
127浏览
2023-12-01
问题描述 (Problem Description)
如何写入文件?
解决方案 (Solution)
此示例显示如何使用BufferedWriter的write方法写入文件。
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
out.write("aString");
out.close();
System.out.println("File created successfully");
}
catch (IOException e) {
}
}
}
结果 (Result)
上面的代码示例将产生以下结果。
File created successfully.
以下是在java中写入文件的另一个例子
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) {
try {
String content = "xnip is one the best site in the world";
File file = new File("C:\\Users\\xnip7\\Desktop\\abc.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
上面的代码示例将产生以下结果。
Done