使用 BufferedWriter 和 JTextFields
Using BufferedWriter and JTextFields
我在使用 BufferedWriter 从文本输入到 JTextField 中将文本写入文件时遇到问题。
问题出现在下面代码中的 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");
}
}
这个问题很含糊,但由于它在 "inputAdd," 中,我假设你想追加到文件中,在这种情况下你的 FileWriter 应该是
BufferedWriter writer = new BufferedWriter(new FileWriter(currentPlaylist, true)); //notice the extra argument
同时将您的 if 语句更改为
if(source == input....)
我在使用 BufferedWriter 从文本输入到 JTextField 中将文本写入文件时遇到问题。
问题出现在下面代码中的 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");
}
}
这个问题很含糊,但由于它在 "inputAdd," 中,我假设你想追加到文件中,在这种情况下你的 FileWriter 应该是
BufferedWriter writer = new BufferedWriter(new FileWriter(currentPlaylist, true)); //notice the extra argument
同时将您的 if 语句更改为
if(source == input....)