使用PrintStream附加到文本文件

Twi*_*tar 2 java append printstream

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

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

已编辑: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;

}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 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(....) {
  // ....
}
Run Code Online (Sandbox Code Playgroud)

编辑:
要将此应用于上面发布的代码,请执行以下操作:

   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;

   }
Run Code Online (Sandbox Code Playgroud)

关键是这些线路在这里:

            File file = chooser.getSelectedFile();
            FileOutputStream fos = new FileOutputStream(file, true);
            return new PrintStream(fos);
Run Code Online (Sandbox Code Playgroud)

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