Click here to Skip to main content
15,949,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am facing a problem using a file chooser in a jframe. I want to save a file in a specific place using file chooser and open a file from the specific place.
Posted

Try using this code for your close, open, save buttons:

Java
public void actionPerformed(ActionEvent e) {

		if(e.getSource()==close){
			this.dispose();
		}
		
		if(e.getSource()==open){
			
			JFileChooser choose=new JFileChooser();  //create a new JFileChooser instance
		
			int option=choose.showOpenDialog(this);
			if(option==JFileChooser.APPROVE_OPTION){  // ok button in dialog chose frame
				
				this.textArea.setText(" ");
				try {
					
					Scanner scan=new Scanner(new FileReader(choose.getSelectedFile().getPath()));  
				
   //you need a scanner to read lines in your text file, a stream FileReader to read the text file
					while(scan.hasNext()){
						textArea.append(scan.nextLine()+"\n");
					}
					
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				}
				
			}
			
		}// open getSource()
		
		if(e.getSource()==save){
			
			JFileChooser save=new JFileChooser();
			int option=save.showSaveDialog(this);
			
			if(option==JFileChooser.APPROVE_OPTION){
				
				try {
					BufferedWriter bw=new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));  //a bufferedwriter( a high level stream writer )
					bw.write(textArea.getText());
					bw.close();
					
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			
		}
		
	}
 
Share this answer
 
Please find an example here. Refer to this link as well.

Cheers,
Sudhakar
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900