java - 添加到文件而不是覆盖

标签 java csv

我编写了一个程序,它抓取了两次源代码,并从检索到的数据中创建了一个包含特定信息的 CSV。我的问题是,当我去保存第二位数据时,它没有添加到创建的 CSV 中,而是用新信息覆盖了它。我已经提到这个 link ,但它使用的是不同的类。我的代码目前是:

  public static void scrapeWebsite() throws IOException {


    final WebClient webClient = new WebClient();
    final HtmlPage page = webClient.getPage(s);
    originalHtml = page.getWebResponse().getContentAsString();
    obtainInformation();
    originalHtml = "";
    final HtmlForm form = page.getForms().get(0);
    final HtmlSubmitInput button = form.getInputByValue(">");
    final HtmlPage page2 = button.click();
    try {
      synchronized (page2) {
        page2.wait(1000);
      }
    }
    catch(InterruptedException e)
    {
      System.out.println("error");
    }
    originalHtml = originalHtml + page2.refresh().getWebResponse().getContentAsString();
    obtainInformation();
  }

  public static void obtainInformation() throws IOException {

     PrintWriter docketFile = new PrintWriter(new FileWriter("tester3.csv", true));

//创建 csv 文件。 (必须更改名称,覆盖删除文件) originalHtml = originalHtml.replace('"','*'); 整数 i = 0;

    //While loop runs through all the data in the source code. There is (14) entries per page.
    while(i<14) {
      String plaintiffAtty = "PlaintiffAtty_"+i+"*>"; //creates the search string for the plaintiffatty
      Pattern plaintiffPattern = Pattern.compile("(?<="+Pattern.quote(plaintiffAtty)+").*?(?=</span>)");//creates the pattern for the atty
      Matcher plaintiffMatcher = plaintiffPattern.matcher(originalHtml); // looks for a match for the atty

      while (plaintiffMatcher.find()) {
        docketFile.write(plaintiffMatcher.group().toString()+", "); //writes the found atty to the file
      }
      i++;
    }
    docketFile.close(); //closes the file 
  } 
}

我相信必须在第二种方法中进行更改。

最佳答案

您的 PrintWriter 应该引用 FileWriter将附加构造函数 boolean 值设置为 true 进行构造。

例如

new PrintWriter(new FileWriter("myfile.csv", true));

请注意 FileWriter 的 Javadoc。您的编码规范:

Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

关于java - 添加到文件而不是覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19571398/

相关文章:

Java认证: How to override methods that define a throws exception?

php - 安装插件时加载data.csv

python以相同的顺序将字典保存到csv

java - Log4J 控制台附加程序编码

java - 尝试使用Java从组合框生成文本框字段

javascript - 如何将 JavaScript 对象数据添加到 HTML

Python 子进程在 .csv : 'unexpected eof' 上调用 bcp

python - 处理 Python 中的越界/写入 CSV

java - 使用 SLF4J,是否可以对错误/警告采取行动?

java - 在一项 Activity 中添加两个 GalleryView