在java中如何追加文本到存在的文件中?
如果你只需要执行一次,则使用Files类很容易:
try { Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND); }catch (IOException e) { //exception handling left as an exercise for the reader }
注意:NoSuchFileException如果文件不存在,上述方法将抛出。它还不会自动追加换行符(追加到文本文件时通常会需要此换行符)。
但是,如果你要多次写入同一文件,则上述操作必须多次打开和关闭磁盘上的文件,这是一个缓慢的操作。在这种情况下,使用缓冲写入器更好:
try(FileWriter fw = new FileWriter("myfile.txt", true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println("the text"); //more code out.println("more text"); //more code } catch (IOException e) { //exception handling left as an exercise for the reader }
笔记:
FileWriter
BufferedWriter
PrintWriter
println
System.out
try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true))); out.println("the text"); out.close(); } catch (IOException e) { //exception handling left as an exercise for the reader }
如果你需要对旧版Java进行健壮的异常处理,它将变得非常冗长:
FileWriter fw = null; BufferedWriter bw = null; PrintWriter out = null; try { fw = new FileWriter("myfile.txt", true); bw = new BufferedWriter(fw); out = new PrintWriter(bw); out.println("the text"); out.close(); } catch (IOException e) { //exception handling left as an exercise for the reader } finally { try { if(out != null) out.close(); } catch (IOException e) { //exception handling left as an exercise for the reader } try { if(bw != null) bw.close(); } catch (IOException e) { //exception handling left as an exercise for the reader } try { if(fw != null) fw.close(); } catch (IOException e) { //exception handling left as an exercise for the reader } }