我需要在Java中反复向现有文件追加文本。我怎么做呢?
当前回答
我只是补充了一个小细节:
new FileWriter("outfilename", true)
2.nd parameter (true) is a feature (or, interface) called appendable (http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html). It is responsible for being able to add some content to the end of particular file/stream. This interface is implemented since Java 1.5. Each object (i.e. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer) with this interface can be used for adding content
换句话说,您可以向gzip文件或http进程添加一些内容
其他回答
您这样做是为了记录日志吗?如果是这样,有几个库。其中最流行的两个是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
}
注意:如果文件不存在,上述方法将抛出NoSuchFileException。它也不会自动追加换行符(当追加到文本文件时,您经常希望这样)。另一种方法是同时传递CREATE和APPEND选项,如果文件不存在,则会先创建文件:
private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
CREATE, APPEND
);
}
但是,如果要多次写入同一个文件,那么上面的代码段必须多次打开和关闭磁盘上的文件,这是一个缓慢的操作。在这种情况下,BufferedWriter会更快:
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构造函数的第二个参数将告诉它追加到文件中,而不是写入一个新文件。(如果该文件不存在,将创建该文件。) 对于昂贵的写入器(如FileWriter),建议使用BufferedWriter。 使用PrintWriter可以访问您可能在System.out中习惯的println语法。 但是BufferedWriter和PrintWriter包装器并不是严格必要的。
老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 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
}
}
最好使用try-with-resources,而不是java 7之前的所有业务
static void appendStringToFile(Path file, String s) throws IOException {
try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
out.append(s);
out.newLine();
}
}
FileOutputStream stream = new FileOutputStream(path, true);
try {
stream.write(
string.getBytes("UTF-8") // Choose your encoding.
);
} finally {
stream.close();
}
然后在上游某处捕获IOException。
String str;
String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new FileWriter(path, true));
try
{
while(true)
{
System.out.println("Enter the text : ");
str = br.readLine();
if(str.equalsIgnoreCase("exit"))
break;
else
pw.println(str);
}
}
catch (Exception e)
{
//oh noes!
}
finally
{
pw.close();
}
这将达到你的目的。
确保流在所有场景中都正确关闭。
有些令人担忧的是,这些答案中有许多在出现错误时将文件句柄保持打开状态。https://stackoverflow.com/a/15053443/2498188的答案是正确的,但只是因为BufferedWriter()不能抛出。如果可以,则异常将使FileWriter对象打开。
一种更通用的方法,它不关心BufferedWriter()是否会抛出:
PrintWriter out = null;
BufferedWriter bw = null;
FileWriter fw = null;
try{
fw = new FileWriter("outfilename", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
finally{
try{
if( out != null ){
out.close(); // Will close bw and fw too
}
else if( bw != null ){
bw.close(); // Will close fw too
}
else if( fw != null ){
fw.close();
}
else{
// Oh boy did it fail hard! :3
}
}
catch( IOException e ){
// Closing the file writers failed for some obscure reason
}
}
编辑:
从Java 7开始,推荐的方法是使用“try with resources”,让JVM来处理:
try( FileWriter fw = new FileWriter("outfilename", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)){
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
推荐文章
- 如何添加JTable在JPanel与空布局?
- Statement和PreparedStatement的区别
- 我如何创建目录,如果它不存在,以创建文件?
- 为什么不能在Java中扩展注释?
- 在Java中使用UUID的最重要位的碰撞可能性
- 转换列表的最佳方法:map还是foreach?
- 如何分割逗号分隔的字符串?
- Java字符串—查看字符串是否只包含数字而不包含字母
- Mockito.any()传递带有泛型的接口
- 在IntelliJ 10.5中运行测试时,出现“NoSuchMethodError: org.hamcrest. matcher . descripbemismatch”
- 使用String.split()和多个分隔符
- Java数组有最大大小吗?
- 在Android中将字符串转换为Uri
- 从JSON生成Java类?
- 为什么java.util.Set没有get(int index)?