提问人:flyingfromchina 提问时间:10/26/2009 最后编辑:Steve Chambersflyingfromchina 更新时间:7/19/2022 访问量:1226934
如何在Java中将文本附加到现有文件中?
How to append text to an existing file in 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
}
注意:如果文件尚不存在,上述方法将抛出一个。它也不会自动附加换行符(在附加到文本文件时经常需要换行符)。另一种方法是传递 both 和 options,如果文件尚不存在,它将首先创建文件: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
);
}
但是,如果您要多次写入同一个文件,则上述代码片段必须多次打开和关闭磁盘上的文件,这是一个缓慢的操作。在本例中,a 速度更快: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
- 对于昂贵的编写器(例如 ),建议使用 a 。
BufferedWriter
FileWriter
- 使用 a 可以访问您可能习惯的语法。
PrintWriter
println
System.out
- 但是 和 包装器并不是绝对必要的。
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
}
}
评论
new BufferedWriter(...)
FileWriter
close()
out
close()
try
try(FileWriter fw = new FileWriter("myFile.txt")){ Print writer = new ....//code goes here }
flush()
try
StandardOpenOption.APPEND
.getBytes()
catch
您可以将标志设置为 ,用于追加。fileWriter
true
try
{
String filename= "MyFile.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write("add a line\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
评论
try(FileWriter fw = new FileWriter(filename,true)){ // Whatever }catch(IOException ex){ ex.printStackTrace(); }
使用 Apache Commons 2.1:
import org.apache.logging.log4j.core.util.FileUtils;
FileUtils.writeStringToFile(file, "String to append", true);
评论
我只是添加一些小细节:
new FileWriter("outfilename", true)
2.nd 参数 (true) 是称为 appendable (http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html) 的功能(或接口)。它负责能够将一些内容添加到特定文件/流的末尾。此接口从 Java 1.5 开始实现。具有此接口的每个对象(即 BufferedWriter、CharArrayWriter、CharBuffer、FileWriter、FilterWriter、LogStream、OutputStreamWriter、PipedWriter、PrintStream、PrintWriter、StringBuffer、StringBuilder、StringWriter、Writer)都可用于添加内容
换句话说,您可以向 gzip 压缩的文件或一些 http 进程添加一些内容
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();
}
这将做你想要的..
这里所有带有 try/catch 块的答案都不应该将 .close() 部分包含在 finally 块中吗?
标记答案示例:
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
out.println("the text");
} catch (IOException e) {
System.err.println(e);
} finally {
if (out != null) {
out.close();
}
}
此外,从 Java 7 开始,您可以使用 try-with-resources 语句。关闭声明的资源不需要 finally 块,因为它是自动处理的,而且也不那么冗长:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
out.println("the text");
} catch (IOException e) {
System.err.println(e);
}
评论
out
finally
out.close()
flush
示例,使用 Guava:
File to = new File("C:/test/test.csv");
for (int i = 0; i < 42; i++) {
CharSequence from = "some string" + i + "\n";
Files.append(from, to, Charsets.UTF_8);
}
评论
FileOutputStream stream = new FileOutputStream(path, true);
try {
stream.write(
string.getBytes("UTF-8") // Choose your encoding.
);
} finally {
stream.close();
}
然后在上游的某个地方捕获 IOException。
使用 java.nio。文件以及 java.nio.file。标准OpenOption
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();
这将创建一个接受参数的 using Files,并从结果中自动刷新 。的方法,然后可以调用该方法写入文件。BufferedWriter
StandardOpenOption
PrintWriter
BufferedWriter
PrintWriter
println()
此代码中使用的参数:打开文件进行写入,仅追加到文件中,如果文件不存在,则创建文件。StandardOpenOption
Paths.get("path here")
可以替换为 。
并且可以修改以适应所需的.new File("path here").toPath()
Charset.forName("charset name")
Charset
我可能会推荐 apache commons 项目。这个项目已经提供了一个框架来做你需要的事情(即灵活的集合过滤)。
确保在所有情况下都正确关闭流。
在发生错误时,这些答案中有多少会让文件句柄保持打开状态,这有点令人震惊。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 开始,推荐的方法是使用“尝试使用资源”并让 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.
}
评论
PrintWriter.close()
throws IOException
close()
IOException
PrintWriter.checkError()
out.close()
XX.close()
out.close()
bw.close()
fw.close()
fw
在项目中的任何位置创建一个函数,只需在需要的地方调用该函数即可。
伙计们,你们要记住,你们正在调用活动线程,而这些线程不是异步调用的,因为要正确完成它可能需要 5 到 10 页。 为什么不花更多的时间在你的项目上,而忘记写任何已经写好的东西。 适当地
//Adding a static modifier would make this accessible anywhere in your app
public Logger getLogger()
{
return java.util.logging.Logger.getLogger("MyLogFileName");
}
//call the method anywhere and append what you want to log
//Logger class will take care of putting timestamps for you
//plus the are ansychronously done so more of the
//processing power will go into your application
//from inside a function body in the same class ...{...
getLogger().log(Level.INFO,"the text you want to append");
...}...
/*********log file resides in server root log files********/
三行代码,第二行,因为第三行实际上附加了文本。:P
图书馆
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
法典
public void append()
{
try
{
String path = "D:/sample.txt";
File file = new File(path);
FileWriter fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
fileWriter.append("Sample text in the file to append");
bufferFileWriter.close();
System.out.println("User Registration Completed");
}catch(Exception ex)
{
System.out.println(ex);
}
}
你也可以试试这个:
JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file
try
{
RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
long length = raf.length();
//System.out.println(length);
raf.setLength(length + 1); //+ (integer value) for spacing
raf.seek(raf.length());
raf.writeBytes(Content);
raf.close();
}
catch (Exception e) {
//any exception handling method of ur choice
}
最好使用 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();
}
}
在 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);
评论
以下方法允许您将文本附加到某个文件:
private void appendToFile(String filePath, String text)
{
PrintWriter fileWriter = null;
try
{
fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(
filePath, true)));
fileWriter.println(text);
} catch (IOException ioException)
{
ioException.printStackTrace();
} finally
{
if (fileWriter != null)
{
fileWriter.close();
}
}
}
或者使用 FileUtils
:
public static void appendToFile(String filePath, String text) throws IOException
{
File file = new File(filePath);
if(!file.exists())
{
file.createNewFile();
}
String fileContents = FileUtils.readFileToString(file);
if(file.length() != 0)
{
fileContents = fileContents.concat(System.lineSeparator());
}
fileContents = fileContents.concat(text);
FileUtils.writeStringToFile(file, fileContents);
}
它效率不高,但工作正常。换行符得到正确处理,如果换行符尚不存在,则创建一个新文件。
评论
尝试使用 bufferFileWriter.append,它适用于我。
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);
}
评论
如果我们使用的是 Java 7 及以上版本,并且也知道要添加(附加)到文件中的内容,我们可以在 NIO 包中使用 newBufferedWriter 方法。
public static void main(String[] args) {
Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
String text = "\n Welcome to Java 8";
//Writing to the file temp.txt
try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
有几点需要注意:
- 指定字符集编码始终是一个好习惯,为此我们在类中有常量。
StandardCharsets
- 该代码使用在尝试后自动关闭资源的语句。
try-with-resource
虽然 OP 没有询问,但以防万一我们想搜索具有某些特定关键字的行,例如 我们可以在 Java 中使用流 API:confidential
//Reading from the file the first line which contains word "confidential"
try {
Stream<String> lines = Files.lines(FILE_PATH);
Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
if(containsJava.isPresent()){
System.out.println(containsJava.get());
}
} catch (IOException e) {
e.printStackTrace();
}
评论
write(String string)
newLine()
我的回答:
JFileChooser chooser= new JFileChooser();
chooser.showOpenDialog(chooser);
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";
try
{
RandomAccessFile random = new RandomAccessFile(file, "rw");
long length = random.length();
random.setLength(length + 1);
random.seek(random.length());
random.writeBytes(Content);
random.close();
}
catch (Exception exception) {
//exception handling
}
这可以在一行代码中完成。希望这对:)有所帮助
Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);
评论
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);
true 允许在现有文件中附加数据。如果我们将写
FileOutputStream fos = new FileOutputStream("File_Name");
它将覆盖现有文件。所以选择第一种方法。
此代码将满足您的需求:
FileWriter fw=new FileWriter("C:\\file.json",true);
fw.write("ssssss");
fw.close();
评论
/**********************************************************************
* it will write content to a specified file
*
* @param keyString
* @throws IOException
*********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
// For output to file
File a = new File(textFilePAth);
if (!a.exists()) {
a.createNewFile();
}
FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(keyString);
bw.newLine();
bw.close();
}// end of writeToFile()
评论
如果你想在特定行中添加一些文本,你可以先阅读整个文件,将文本附加到任何你想要的地方,然后覆盖所有内容,如下面的代码所示:
public static void addDatatoFile(String data1, String data2){
String fullPath = "/home/user/dir/file.csv";
File dir = new File(fullPath);
List<String> l = new LinkedList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
String line;
int count = 0;
while ((line = br.readLine()) != null) {
if(count == 1){
//add data at the end of second line
line += data1;
}else if(count == 2){
//add other data at the end of third line
line += data2;
}
l.add(line);
count++;
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
createFileFromList(l, dir);
}
public static void createFileFromList(List<String> list, File f){
PrintWriter writer;
try {
writer = new PrintWriter(f, "UTF-8");
for (String d : list) {
writer.println(d.toString());
}
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Writer {
public static void main(String args[]){
doWrite("output.txt","Content to be appended to file");
}
public static void doWrite(String filePath,String contentToBeAppended){
try(
FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)
)
{
out.println(contentToBeAppended);
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
}
}
评论
稍微扩展一下Kip的回答, 下面是一个简单的 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...
}
更多说明:
上面使用了
Files.write
重载,该重载将文本行写入文件(即类似于命令)。为了将文本写入末尾(即类似于命令),可以使用替代的Files.write
重载,传入字节数组(例如 )。println
print
"mytext".getBytes(StandardCharsets.UTF_8)
该选项仅在指定的目录已存在时才有效 - 如果不存在,则抛出 a。如果需要,可以在设置创建目录结构后添加以下代码:
CREATE
NoSuchFileException
path
Path pathParent = path.getParent(); if (!Files.exists(pathParent)) { Files.createDirectories(pathParent); }
评论
.CREATE
.CREATE
APPEND
CREATE
Files.write(Paths.get("test.log"), (Instant.now().toString() + "\r\n").getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
您可以使用 follong 代码将内容附加到文件中:
String fileName="/home/shriram/Desktop/Images/"+"test.txt";
FileWriter fw=new FileWriter(fileName,true);
fw.write("here will be you content to insert or append in file");
fw.close();
FileWriter fw1=new FileWriter(fileName,true);
fw1.write("another content will be here to be append in the same file");
fw1.close();
爪哇 7+
以我的拙见,因为我是纯 Java 的粉丝,我会建议它是上述答案的组合。也许我参加聚会迟到了。代码如下:
String sampleText = "test" + System.getProperty("line.separator");
Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
如果文件不存在,则创建该文件,如果已存在,则将 sampleText 追加到现有文件。使用它,可以避免向类路径添加不必要的库。
对于 JDK 版本 >= 7
您可以使用以下简单方法将给定内容附加到指定文件:
void appendToFile(String filePath, String content) {
try (FileWriter fw = new FileWriter(filePath, true)) {
fw.write(content + System.lineSeparator());
} catch (IOException e) {
// TODO handle exception
}
}
我们正在以追加模式构造一个 FileWriter 对象。
评论