如何在Java中向现有文件追加文本?
我需要在Java中重复向现有文件追加文本。我该怎么做?您这样做是为了记录日志吗?如果有的话。最受欢迎的两种是和 爪哇7+ 对于一次性任务,可以简化此操作:如何在Java中向现有文件追加文本?,java,file-io,io,text-files,Java,File Io,Io,Text Files,我需要在Java中重复向现有文件追加文本。我该怎么做?您这样做是为了记录日志吗?如果有的话。最受欢迎的两种是和 爪哇7+ 对于一次性任务,可以简化此操作: try { Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND); }catch (IOException e) { //exception handling left
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可以访问println语法,您可能已经习惯于从System.out访问该语法。
但是BufferedWriter和PrintWriter包装器并不是严格必需的。
旧爪哇
异常处理
如果您需要对旧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
}
}
您可以使用标记设置为true的fileWriter进行追加
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());
}
使用Apache Commons 2.1:
FileUtils.writeStringToFile(file, "String to append", true);
我只添加了一些小细节:
new FileWriter("outfilename", true)
2.nd参数true是一个称为appendable的功能或接口。它负责将一些内容添加到特定文件/流的末尾。这个接口是从Java1.5开始实现的。每个对象(即BufferedWriter、CharrayWriter、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块的答案不都应该包含finally块中的.close块吗 标记答案示例:
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();
}
}
另外,从Java7开始,您可以使用。关闭声明的资源不需要finally块,因为它是自动处理的,而且也不太详细:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
out.println("the text");
} catch (IOException e) {
System.err.println(e);
}
样本,使用番石榴:
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);
}
然后使用java.nio捕获上游某处的IOException。。以及java.nio.file
这将使用接受StandardOpenOption参数的文件创建BufferedWriter,并从生成的BufferedWriter创建自动刷新PrintWriter。然后可以调用PrintWriter的println方法来写入文件
此代码中使用的StandardOpenOption参数:打开文件进行写入,仅附加到文件,如果文件不存在,则创建文件
此处的Paths.getpath可以替换为新的Filepath here.toPath。
和Charset.forname可以修改Charset name以适应所需的字符集。我建议使用。这个项目已经提供了一个框架来完成您需要的工作,即灵活地筛选集合 确保在所有场景中正确关闭流。
如果出现错误,这些答案中有多少会让文件句柄保持打开状态,这有点令人担忧。答案在于钱,但只是因为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.
}
在项目中的任何地方创建一个函数,并在需要时调用该函数 伙计们,你们要记住,你们在调用活动线程,而不是异步调用,因为这可能需要5到10页才能正确完成。 为什么不花更多的时间在你的项目上,忘掉已经写过的东西呢。 恰当地 代码2的三行实际上是因为第三行实际上附加了文本:P 图书馆 代码
您也可以尝试以下方法:
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比使用Java7之前的所有业务更好
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();
}
}
}
或者使用:
它效率不高,但运行良好。换行符处理正确,如果还不存在,则会创建一个新文件。尝试使用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);
}
如果我们使用的是Java7及以上版本,并且知道要添加到文件中的内容,那么我们可以使用NIO包中的方法
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();
}
}
有几点需要注意:
指定字符集编码始终是一个好习惯,为此,我们在类StandardCharset中使用常量
.
代码使用try with resource语句,在该语句中,资源在try之后自动关闭。
虽然OP没有询问,但只是为了防止我们想要搜索具有特定关键字(例如机密)的行,我们可以使用Java中的流API:
//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();
}
我的答覆是:
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);
true允许将数据附加到现有文件中。如果我们写
FileOutputStream fos = new FileOutputStream("File_Name");
它将覆盖现有文件。因此,选择第一种方法。此代码将满足您的需要:
FileWriter fw=new FileWriter("C:\\file.json",true);
fw.write("ssssss");
fw.close();
如果您想在特定行中添加一些文本,您可以先读取整个文件,将文本附加到任何位置,然后覆盖所有内容,如下面的代码所示:
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();
}
}
稍有扩展,,
下面是一个简单的Java 7+方法,用于将新行追加到文件中,并在文件不存在时创建它:
private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
CREATE, APPEND
);
}
进一步说明:
上面使用的重载将文本行写入文件,即类似于println命令。要仅将文本写入末尾,即类似于打印命令,可以使用另一种重载,传入字节数组,例如mytext.getBytesStandardCharsets.UTF_8
仅当指定的目录已存在时,CREATE选项才起作用-如果不存在,则引发NoSuchFileException。如果需要,可以在设置路径后添加以下代码以创建目录结构:
Path pathParent = path.getParent();
if (!Files.exists(pathParent)) {
Files.createDirectories(pathParent);
}
您可以使用以下代码将内容追加到文件中:
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添加到现有文件。使用此选项,可以避免向类路径添加不必要的lib。对于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
}
}
我们正在以追加模式构造对象。哦,谢谢。我被所有其他答案的复杂性逗乐了。我真的不明白为什么人们喜欢把开发人员的生活复杂化。这种方法的问题是每次都会打开和关闭输出流。根据您写入文件的内容和频率,这可能会导致荒谬的开销。@Buffalo是对的。但在将其写入文件之前,您始终可以使用StringBuilder构建值得写入的大块。@KonstantinK但之后您需要写入的所有内容都会加载到内存中。当out超出范围时,它会在垃圾回收时自动关闭,对吗?在使用finally块的示例中,我认为您实际上需要另一个嵌套的try/catch out.close(如果我没记错的话)。Java7解决方案非常灵活!自从Java6以来,我没有做过任何Java开发,所以我不熟悉这种变化。@Kip不,超出范围在Java中没有任何作用。该文件将在将来的某个随机时间关闭。可能在节目结束时closes@etech第二种方法是否需要flush方法?您应该使用java7 try with resources,或者将close放在finally块中,以确保在出现异常时关闭文件。。。抛出异常;文件写入程序将关闭吗?我猜它不会被关闭,因为在正常情况下关闭方法将在out对象上被调用,在这种情况下,它不会被初始化-因此实际上关闭方法不会被调用->文件将被打开,但不会被关闭。因此,我希望try语句看起来像这个tryFileWriter fw=newfilewritermyfile.txt{Print writer=new..//code goes here},他应该在退出try块之前刷新writer!!!注意,如果在try块中抛出异常,旧的java示例将无法正确关闭流。java 7方法可能存在两个问题:1如果文件不存在,StandardOpenOption.APPEND将不会创建它-有点像无声故障,因为它也不会抛出异常。2使用.getBytes意味着在附加文本之前或之后没有返回字符。已经添加了一个地址来解决这些问题。谢谢您的输入。如果文件不存在,我不相信append模式不会创建该文件,所以我必须尝试确认。不知道他们在想什么。。。我发现它实际上抛出了一个异常,但是如果复制/粘贴我的代码并将catch块留空,那么就看不到它。我已经更新了我的答案,以反映这些问题,并添加了一个链接到您的答案。这是一个可怕的建议。您将文件流打开42次而不是一次。@xehpuk好吧,这取决于您。42仍然可以,如果它使代码更具可读性的话。42k是不可接受的。close应该放在finally块中,就像中所示,以防在创建FileWriter和调用之间抛出异常
正在关闭。回答很好,但最好使用System.getProperty line.separator作为新行,而不是\n。@Decoded我已回滚您对此答案的编辑,因为它不编译。@Kip,有什么问题吗?我一定输入了错别字。用资源试试怎么样?tryFileWriter fw=new FileWriterfilename,true{//Whatever}catchIOException ex{ex.printStackTrace;}需要导入什么?这些东西使用哪个库?+1表示Java 7的正确ARM。关于这个棘手的主题,这里有一个很好的问题:。嗯,出于某种原因,PrintWriter.close在中没有声明为抛出IOException。仔细看,close方法确实不能抛出IOException,因为它从底层流捕获IOException,并设置标志。因此,如果您正在为下一个航天飞机或X射线剂量测量系统编写代码,您应该在尝试out.close后使用PrintWriter.checkError。这真的应该被记录下来。如果我们对关闭非常偏执,那么每个XX.close都应该有自己的try/catch,对吗?例如,out.close可能会引发异常,在这种情况下,永远不会调用bw.close和fw.close,而fw是关闭最关键的一个。警告:当使用BufferedWriter writeString时,如果希望在写入每个字符串后都有新行,则应调用换行符。。。什么这将覆盖文件。这里的obj.toJSONString是什么?@Bhaskarani这只是一个字符串,他举了一个JSON对象转换为字符串的例子,但想法是它可以是任何字符串。以上只是所提供解决方案的一个快速示例实现。因此,您可以复制并运行代码,并立即了解其工作原理,确保output.out文件与Writer.java文件位于同一目录中。这可能还不够:更好的版本是Files.writePath.getfileName、msg.getBytes、StandardOpenOption.APPEND、StandardOpenOption.CREATE;是否需要检查该文件是否存在?我认为.CREATE可以帮你完成这项工作。如果在文件已经存在的情况下使用.CREATE,那么它将以静默方式无法追加任何内容-不会引发异常,但现有文件内容保持不变。使用append+CREATE可以完美地工作,无需检查:Files.writePath.gettest.log,Instant.now.toString+\r\n.getBytes,StandardOpenOption.CREATE,StandardOpenOption.APPEND;
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.
}
}
}
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...
}
Path pathParent = path.getParent();
if (!Files.exists(pathParent)) {
Files.createDirectories(pathParent);
}
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();
String sampleText = "test" + System.getProperty("line.separator");
Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
void appendToFile(String filePath, String content) {
try (FileWriter fw = new FileWriter(filePath, true)) {
fw.write(content + System.lineSeparator());
} catch (IOException e) {
// TODO handle exception
}
}