我需要在Java中反复向现有文件追加文本。我怎么做呢?
当前回答
尝试使用bufferFileWriter。附加,它对我有用。
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
bufferFileWriter.append(obj.toJSONString());
bufferFileWriter.newLine();
bufferFileWriter.close();
} catch (IOException ex) {
Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
其他回答
我只是补充了一个小细节:
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进程添加一些内容
使用Apache Commons 2.1:
import org.apache.logging.log4j.core.util.FileUtils;
FileUtils.writeStringToFile(file, "String to append", true);
使用java.nio.Files和java.nio.file.StandardOpenOption
PrintWriter out = null;
BufferedWriter bufWriter;
try{
bufWriter =
Files.newBufferedWriter(
Paths.get("log.txt"),
Charset.forName("UTF8"),
StandardOpenOption.WRITE,
StandardOpenOption.APPEND,
StandardOpenOption.CREATE);
out = new PrintWriter(bufWriter, true);
}catch(IOException e){
//Oh, no! Failed to create PrintWriter
}
//After successful creation of PrintWriter
out.println("Text to be appended");
//After done writing, remember to close!
out.close();
这将使用Files创建一个BufferedWriter,它接受StandardOpenOption参数,并从结果BufferedWriter创建一个自动刷新的PrintWriter。然后可以调用PrintWriter的println()方法来写入文件。
这段代码中使用的StandardOpenOption参数:打开文件进行写入,仅追加到文件中,并在文件不存在时创建文件。
路径。get("path here")可以用new File("path here"). topath()代替。 和字符集。forName(“字符集名称”)可以修改以适应所需的字符集。
稍微扩展一下基普的回答, 下面是一个简单的Java 7+方法来追加一个新行到一个文件,如果它不存在就创建它:
try {
final Path path = Paths.get("path/to/filename.txt");
Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
// Add your own exception handling...
}
进一步指出:
The above uses the Files.write overload that writes lines of text to a file (i.e. similar to a println command). To just write text to the end (i.e. similar to a print command), an alternative Files.write overload can be used, passing in a byte array (e.g. "mytext".getBytes(StandardCharsets.UTF_8)). The CREATE option will only work if the specified directory already exists - if it doesn't, a NoSuchFileException is thrown. If required, the following code could be added after setting path to create the directory structure: Path pathParent = path.getParent(); if (!Files.exists(pathParent)) { Files.createDirectories(pathParent); }
在Java-7中也可以这样做:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
//---------------------
Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);
推荐文章
- 如何添加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)?