Search code examples
javajtextfieldfilewriterbufferedwriter

Using BufferedWriter and JTextFields


I am having problems writing text to a file using BufferedWriter from text input into a JTextField.

The problem is occurring at the event.getSource == inputAdd statement in the below code.

public void actionPerformed(ActionEvent event){

  Object source = event.getSource();

  if (event.getSource() == inputOpen){       
    file.openFile(inputOpenFile.getText());
    currentPlaylist = file.getFileName();
    contentList.setText(file.fileRead()); //read file
    contentTitle.setText("Current Movie Playlist: " + currentPlaylist); //set text to what's in file
  }

  if (event.getSource() == inputCreate){
    file.createFile(inputCreateFile.getText());
    currentPlaylist = file.getFileName();
    inputCreateFile.setText(""); //set text to nothing 
  }

  if (event.getSource() == inputAdd){      
    //file.openFile(inputOpenFile.getText());
    //file.createElement(inputAddMovie.getText());

    movie = inputAddMovie.getText();

    try{
      BufferedWriter writer = new BufferedWriter(new FileWriter(currentPlaylist));
      writer.write(movie);
      writer.newLine();
      writer.close();
    }catch(Exception error){
      System.out.println("There was an error");
    }


  }

Solution

  • This question is pretty vague, but since its in "inputAdd," I will just assume you want to append to the file in which case your FileWriter should be

    BufferedWriter writer = new BufferedWriter(new FileWriter(currentPlaylist, true)); //notice the extra argument
    

    http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,%20boolean)

    Also change your if statements to be

    if(source == input....)