4 回答

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超5個(gè)贊
創(chuàng)建文本文件:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
創(chuàng)建二進(jìn)制文件:
byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();
Java 7+用戶可以使用Files該類寫入文件:
創(chuàng)建文本文件:
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);
創(chuàng)建二進(jìn)制文件:
byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);

TA貢獻(xiàn)1795條經(jīng)驗(yàn) 獲得超7個(gè)贊
在Java 7及更高版本中:
try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("filename.txt"), "utf-8"))) { writer.write("something");}
但是有一些有用的實(shí)用程序:
來(lái)自commons-io的FileUtils.writeStringtoFile(..)
來(lái)自番石榴的Files.write(..)
另請(qǐng)注意,您可以使用a FileWriter
,但它使用默認(rèn)編碼,這通常是一個(gè)壞主意 - 最好明確指定編碼。
以下是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*/}}
另請(qǐng)參閱:讀取,寫入和創(chuàng)建文件(包括NIO2)。

TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果您已經(jīng)擁有要寫入文件的內(nèi)容(而不是動(dòng)態(tài)生成),則java.nio.file.Files
Java 7中作為本機(jī)I / O的一部分添加提供了實(shí)現(xiàn)目標(biāo)的最簡(jiǎn)單,最有效的方法。
基本上創(chuàng)建和寫入文件只是一行,而且一個(gè)簡(jiǎn)單的方法調(diào)用!
以下示例創(chuàng)建并寫入6個(gè)不同的文件以展示如何使用它:
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貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個(gè)贊
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(); } } }}
添加回答
舉報(bào)