使用PrintStream附加到文本文件

时间:2012-03-21 12:52:31

标签: java append printstream

我无法将文本附加到文本文件中,它只会覆盖以前的文本。我的代码:

//using JFileChooser to select where to save file
PrintStream outputStream = MyFrame.ShowSaveDialog();
    if(outputStream!=null){
        outputStream.append(input);
        outputStream.close();
    } 

编辑: ShowSaveDialog返回一个PrintStream。以下是该方法的代码:

public static PrintStream ShowSaveDialog(){
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "Tekst filer", "txt");
    chooser.setFileFilter(filter);

    int returnVal = chooser.showSaveDialog(null);
    try{
        if(returnVal == JFileChooser.APPROVE_OPTION){

            return new PrintStream(chooser.getSelectedFile());              
        }
        else{
            return null;
        } 
    }
    catch(FileNotFoundException e){
        JOptionPane.showMessageDialog(null, "Ugyldig Fil!",
                   "error", JOptionPane.ERROR_MESSAGE);
    }
    return null;

}

1 个答案:

答案 0 :(得分:8)

MyFrame.ShowSaveDialog();返回什么?关键是使用适当的构造函数创建FileOutputStream(第二个参数应该是布尔true),这将使其成为附加的FileOutputStream,然后使用此FileOutputStream对象构造PrintStream。

例如,如果showSaveDialog()(注意方法和变量名称应以小写字母开头)返回文件名或File对象,则可以执行以下操作:

try {
  File file = myFrame.showSaveDialog(); // if this method returns a File!!!!!
  FileOutputStream fos = new FileOutputStream(file, true);
  PrintStream printStream = new PrintStream(fos);
  //.... etc
} catch(....) {
  // ....
}

修改
要将其应用于上面发布的代码,请执行以下操作:

   public static PrintStream showSaveDialog() {
      JFileChooser chooser = new JFileChooser();
      FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "Tekst filer", "txt");
      chooser.setFileFilter(filter);

      int returnVal = chooser.showSaveDialog(null);
      try {
         if (returnVal == JFileChooser.APPROVE_OPTION) {

            //  ******* note changes below *****
            File file = chooser.getSelectedFile();

            FileOutputStream fos = new FileOutputStream(file, true);
            return new PrintStream(fos);
         } else {
            return null;
         }
      } catch (FileNotFoundException e) {
         JOptionPane.showMessageDialog(null, "Ugyldig Fil!", "error",
               JOptionPane.ERROR_MESSAGE);
      }
      return null;

   }

关键在于这些界限:

            File file = chooser.getSelectedFile();
            FileOutputStream fos = new FileOutputStream(file, true);
            return new PrintStream(fos);

FileOutputStream构造函数中的true创建一个附加到现有文件的FileOutputStream。有关详细信息,请查看FileOutputStream API。