4 回答
TA貢獻1851條經驗 獲得超5個贊
創建文本文件:
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, Charset.forName("UTF-8"));
//Files.write(file, lines, Charset.forName("UTF-8"), StandardOpenOption.APPEND);
創建二進制文件:
byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
TA貢獻1795條經驗 獲得超7個贊
在Java 7及更高版本中:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"))) {
writer.write("something");}但是有一些有用的實用程序:
來自commons-io的FileUtils.writeStringtoFile(..)
來自番石榴的Files.write(..)
另請注意,您可以使用a FileWriter,但它使用默認編碼,這通常是一個壞主意 - 最好明確指定編碼。
以下是Java 7之前的原始答案
Writer writer = null;try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"));
writer.write("Something");} catch (IOException ex) {
// Report} finally {
try {writer.close();} catch (Exception ex) {/*ignore*/}}另請參閱:讀取,寫入和創建文件(包括NIO2)。
TA貢獻1788條經驗 獲得超4個贊
如果您已經擁有要寫入文件的內容(而不是動態生成),則java.nio.file.FilesJava 7中作為本機I / O的一部分添加提供了實現目標的最簡單,最有效的方法。
基本上創建和寫入文件只是一行,而且一個簡單的方法調用!
以下示例創建并寫入6個不同的文件以展示如何使用它:
Charset utf8 = StandardCharsets.UTF_8;List<String> lines = Arrays.asList("1st line", "2nd line");byte[] data = {1, 2, 3, 4, 5};try {
Files.write(Paths.get("file1.bin"), data);
Files.write(Paths.get("file2.bin"), data,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Files.write(Paths.get("file3.txt"), "content".getBytes());
Files.write(Paths.get("file4.txt"), "content".getBytes(utf8));
Files.write(Paths.get("file5.txt"), lines, utf8);
Files.write(Paths.get("file6.txt"), lines, utf8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);} catch (IOException e) {
e.printStackTrace();}TA貢獻1785條經驗 獲得超4個贊
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 ) {
output.close();
}
}
}}添加回答
舉報
