2015-10-08 76 views
0

我在使用BufferedWriter從文本輸入到JTextField中將文本寫入文件時出現問題。使用BufferedWriter和JTextFields

問題發生在下面的代碼中的event.getSource == inputAdd語句中。

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"); 
    } 


    } 

回答

0

這個問題是相當模糊的,但由於其在「inputAdd,」我只是假設你要追加到該文件在這種情況下你的FileWriter應該

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)

還改變你的if語句是

if(source == input....) 
+0

是的,抱歉,我是新來的Java。我想從JTextField的文本追加到文本文件。 inputAdd是一個JButton,它在按下時需要將文本從JTextField附加到文件 – aleks

+0

inputAddMovie是JTextField。 ...仍然有問題 – aleks

+0

@AleksDahlberg我需要更多信息。是拋出的異常?如果是的話,什麼?文件沒有被寫入? – WalterM

相關問題