【问题标题】:Add in already exist text file using java使用java添加已经存在的文本文件
【发布时间】:2018-10-17 14:23:09
【问题描述】:

我正在创建一个 java 应用程序,其中一些文本将存储在一个文本文件中。但是 store 函数将在一个循环中运行,每个循环都会从其他类中获取数据并存储在文本文件中。我希望我的文本文件应该像创建日志一样存储每个周期的数据。这是一段代码:

public void store(){
        File file = new File("PaperRecord.txt");

        try{
            PrintWriter fout = new PrintWriter(file);
            fout.println("Paper Name: " + super.getpSame());
            fout.println("Paper Size: " + super.getpSize());
            fout.println("Paper Year: " + super.getpYear());
            fout.println("Paper Author: " + super.getpAuthor());
            fout.println("Paper Description: " + getpDesc());
            fout.println("Paper Signature: " + getpSign());
            fout.println("Email: " + getPEmail());
            fout.println("");
        }
        catch(FileNotFoundException e){
            //do nothing
        }

    }

使用循环从 main 调用 store 函数:

while(!q.isEmpty()){

                        Papers temp = q.remove();
                        temp.print();
                        temp.store();

                    }

此代码当前的问题是该代码每次都创建新文件 paperrecord 或覆盖现有文件。我希望同一文件向下增加和更新(添加更多文本)

【问题讨论】:

标签: java file append printwriter


【解决方案1】:

Files class 是你亲爱的朋友。

try {
    Files.write(Paths.get("PaperRecord.txt"), "new text appended".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

或者,一个示例工作代码:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class AppendToFileExample {

    private static final String FILENAME = "E:\\test\\PaperRecord.txt";

    public static void main(String[] args) {

        BufferedWriter bw = null;
        FileWriter fw = null;

        try {

            String data = " This is new content";

            File file = new File(FILENAME);

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            // true = append file
            fw = new FileWriter(file.getAbsoluteFile(), true);
            bw = new BufferedWriter(fw);

            bw.write(data);

            System.out.println("Done");

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                if (bw != null)
                    bw.close();

                if (fw != null)
                    fw.close();

            } catch (IOException ex) {

                ex.printStackTrace();

            }
        }

    }
}

【讨论】:

  • 为此导入什么?
  • java.nio.file.*;确保您使用的是 jdk1.7 或更高版本。干杯
  • @TehminaBatool 如果这解决了你的问题,请通过投票让我知道,谢谢。
  • 其实我试过了,但是你给的功能也是覆盖文件不追加
  • @TehminaBatool 只需使用示例工作代码更新我的答案,尝试让我知道
猜你喜欢
  • 2016-05-29
  • 2011-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-12
  • 1970-01-01
  • 2014-08-21
相关资源
最近更新 更多