发布日期:2018-03-26
在Java中如何将文本附加到一个已经存在的文件中+ 查看更多
在Java中如何将文本附加到一个已经存在的文件中
+ 查看更多
发布日期:2018-03-10 10:56
分类:JAVA
浏览次数:155
在Java中,我需要反复的将文本附加到一个已经存在的文件夹中。我该怎么做呢?
回答
你这样做是为了记录的目的吗?如果是这样,有一些库是解决这个问题的。其中最流行的是Log4j和Logback。
Java 7:
如果你只需要这样做一次,使用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 }
但是,如果你将会多次写入同一文件,上面的操作必须对磁盘上的文件进行多次打开和关闭,这是一个缓慢的操作。在这种情况下,缓冲写入更好:
老版本的Java:
try(FileWriter fw = new FileWriter("outfilename", 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 }
使用时,需要注意以下几点:
1. FileWriter 构造函数的第二个参数意味着附加到文件上(而不是写一个新文件)。
2. 对于一个比较大的写入程序(例如FileWriter)推荐使用BufferedWriter 。
3. 使用PrintWriter ,你可以看看println语法,大多数人可能习惯使用System.out方法,但println在这里可能更合适一些。
4. BufferedWriter和PrintWriter 包装不是绝对必要的。
1. FileWriter 构造函数的第二个参数意味着附加到文件上(而不是写一个新文件)。
2. 对于一个比较大的写入程序(例如FileWriter)推荐使用BufferedWriter 。
3. 使用PrintWriter ,你可以看看println语法,大多数人可能习惯使用System.out方法,但println在这里可能更合适一些。
4. BufferedWriter和PrintWriter 包装不是绝对必要的。
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 } }