How to append text to an existing file in Java -
i need append text repeatedly existing file in java. how do that?
are doing logging purposes? if there several libraries this. 2 of popular log4j , logback.
java 7+
if need 1 time, files class makes easy:
try { files.write(paths.get("myfile.txt"), "the text".getbytes(), standardopenoption.append); }catch (ioexception e) { //exception handling left exercise reader }
careful: above approach throw nosuchfileexception
if file not exist. not append newline automatically (which want when appending text file). steve chambers's answer covers how files
class.
however, if writing same file many times, above has open , close file on disk many times, slow operation. in case, buffered writer better:
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 exercise reader }
notes:
- the second parameter
filewriter
constructor tell append file, rather writing new file. (if file not exist, created.) - using
bufferedwriter
recommended expensive writer (suchfilewriter
). - using
printwriter
gives accessprintln
syntax you're usedsystem.out
. - but
bufferedwriter
,printwriter
wrappers not strictly necessary.
older java
try { printwriter out = new printwriter(new bufferedwriter(new filewriter("myfile.txt", true))); out.println("the text"); out.close(); } catch (ioexception e) { //exception handling left exercise reader }
exception handling
if need robust exception handling older java, gets verbose:
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 exercise reader } { try { if(out != null) out.close(); } catch (ioexception e) { //exception handling left exercise reader } try { if(bw != null) bw.close(); } catch (ioexception e) { //exception handling left exercise reader } try { if(fw != null) fw.close(); } catch (ioexception e) { //exception handling left exercise reader } }