Textdatei wird beim Speichern nicht überschrieben, sondern ergänzt

noneofthem

Mitglied
Hallo zusammen,

ich habe zwei Probleme.

1.
Ich schreibe mir einen simplen Texteditor zur Übung. soweit klappt alles, nur beim Speichern hab ich das Problem, dass bereits vorhandene Dateien beim erneuten Speichern nicht überschrieben, sondern nur ergänzt werden, was ja nicht Sinn der Sache ist.

2.
Ich hab noch nicht herausgefunden, wie man es schafft, dass schon im Öffnen-Dialogfenster nur die Dateiformate angezeigt werden, die auch geöffnet werden dürfen. Momentan umgehe ich das, indem ich eine Fehlermeldung ausgebe, wenn jemand etwas öffnen will, das nicht erlaubt ist.

Ich wäre dankbar für jeden Tipp. Hier ist der Code:

Java:
package editor;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

public class Jeditor extends JFrame implements ActionListener {

	public String windowTitle = "jEditor";
	private JEditorPane editPane;
    private JMenuItem newAction;
    private JMenuItem openAction;
    private JMenuItem saveAction;
    private JMenuItem exitAction;
    private JMenuItem copyAction;
    private JMenuItem cutAction;
    private JMenuItem pasteAction;
    private JMenuItem aboutAction;
    private File file;
    private boolean isFileLoaded = false;
    Font editPaneFont = new Font ( "verdana", NORMAL, 12 );
	
	public Jeditor () {
		
		this.setTitle ( windowTitle + " - " + "untitled file" );
		this.setDefaultCloseOperation ( JFrame.DO_NOTHING_ON_CLOSE );
		this.setSize ( new Dimension ( 640, 480 ) );
		this.setLocationRelativeTo ( null );

		
		addWindowListener ( new WindowAdapter() { 
	    
			public void windowClosing ( WindowEvent e ) { 
	            exit(); 
	         } 
	    });
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> MENU
		
		JMenuBar menuBar = new JMenuBar();
		menuBar.setLocation(0, 0);
		
		JMenu fileMenu = new JMenu ( "File" );
	    JMenu editMenu = new JMenu ( "Edit" );
	    JMenu aboutMenu = new JMenu ( "About" );
	    
	    newAction = new JMenuItem ( "New" );
        openAction = new JMenuItem ( "Open" );
        saveAction = new JMenuItem ( "Save" );
        exitAction = new JMenuItem ( "Exit" );
        copyAction = new JMenuItem ( "Copy" );
        cutAction = new JMenuItem ( "Cut" );
        pasteAction = new JMenuItem ( "Paste" );
        aboutAction = new JMenuItem ( "About" );
        
        fileMenu.add ( newAction );
        fileMenu.add ( openAction );
        fileMenu.add ( saveAction );
        fileMenu.addSeparator();
        fileMenu.add ( exitAction );
        
        editMenu.add ( copyAction );
        editMenu.add ( cutAction );
        editMenu.add ( pasteAction );
        
        aboutMenu.add ( aboutAction );

	    menuBar.add ( fileMenu );
	    menuBar.add ( editMenu );
//      menuBar.add ( Box.createHorizontalGlue() ); // activate to place aboutMenu on the right
        menuBar.add ( aboutMenu );
        
        newAction.addActionListener ( this );
        openAction.addActionListener ( this );
        saveAction.addActionListener ( this );
        exitAction.addActionListener ( this );
        
        copyAction.addActionListener ( this );
        cutAction.addActionListener ( this );
        pasteAction.addActionListener ( this );
        
        aboutAction.addActionListener ( this );
        
        
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> EDIT PANE
        
		editPane = new JEditorPane();
		editPane.setFont ( editPaneFont );
		JScrollPane editScrollPane = new JScrollPane(
				
				editPane,
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
		);
		
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ADD STUFF to Window
		
		this.setJMenuBar ( menuBar );
		this.add ( editScrollPane );
		isFileLoaded = true;
		this.setResizable ( true );
		this.setVisible ( true );
	}
	
	public void actionPerformed ( ActionEvent e ) {
		
		if ( e.getActionCommand().equalsIgnoreCase ( "new" ) ) {
			newFile ();
		}
		
		if ( e.getActionCommand().equalsIgnoreCase ( "open" ) ) {
			openFile ();
		}
		
		if ( e.getActionCommand().equalsIgnoreCase ( "save" ) ) {
			saveFile();
		}
		
		if ( e.getActionCommand().equalsIgnoreCase ( "exit" ) ) {
			exit();
		}
		
		if ( e.getActionCommand().equalsIgnoreCase ( "copy" ) ) {
			
		}
		
		if ( e.getActionCommand().equalsIgnoreCase ( "cut" ) ) {
			
		}
		
		if ( e.getActionCommand().equalsIgnoreCase ( "paste" ) ) {
			
		}
		
		if ( e.getActionCommand().equalsIgnoreCase ( "about" ) ) {
			showAbout ();
		}
		
	} // END of actionPerformed()
	
	
	void newFile () {
		
		if ( isFileLoaded == true) {
			
			int newFileQuestion = JOptionPane.showConfirmDialog (
					
					null,
					"Are you sure you want to create a new file?\n" +
					"Unsaved changes on the current file will be lost!",
					"Are you sure?",
					JOptionPane.OK_CANCEL_OPTION
			);
			
			if ( newFileQuestion == JOptionPane.YES_OPTION ) {
				
				editPane.setText ( "" );
				this.setTitle ( windowTitle + " - " + "untitled file" );
				
			} else
				return;
			
		} else {
			
			editPane.setText ( "" );
	
		}
	} // END of newFile()
	
	
	void openFile () {
		
		JFileChooser fileChooser = new JFileChooser ( "." );
		fileChooser.setFileSelectionMode ( JFileChooser.FILES_ONLY );
		fileChooser.setOpaque ( true );
		
		int ret = fileChooser.showDialog ( null, "Select file" );
			    
		if ( ret == JFileChooser.APPROVE_OPTION ) {
		 
		   	File selectedFile = fileChooser.getSelectedFile();
		   	
		   	if ( ( selectedFile.getName().toLowerCase().endsWith ( ".conf" ) ) ||
		   		 ( selectedFile.getName().toLowerCase().endsWith ( ".html" ) ) ||
		   		 ( selectedFile.getName().toLowerCase().endsWith ( ".java" ) ) ||
		   		 ( selectedFile.getName().toLowerCase().endsWith ( ".py"   ) ) ||
		   		 ( selectedFile.getName().toLowerCase().endsWith ( ".rtf"  ) ) ||
		   		 ( selectedFile.getName().toLowerCase().endsWith ( ".txt"  ) ) ||
		   		 ( selectedFile.getName().toLowerCase().endsWith ( ".xml"  ) )
		   	) {
			  
		   		try {
			   		
			   		file = new File ( selectedFile.getAbsolutePath() );
			   		FileReader fileReader = new FileReader( file );
					
					BufferedReader br = new BufferedReader ( fileReader );
					StringBuffer sb = new StringBuffer();
					String eachLine = br.readLine();

					while ( eachLine != null ) {
							
					  sb.append ( eachLine );
					  sb.append ( "\n" );
					  eachLine = br.readLine();
					}
						
					editPane.setText ( sb.toString() );
					editPane.setCaretPosition ( 0 );
					this.setTitle ( windowTitle + " - " + selectedFile.getAbsolutePath() );
					isFileLoaded = true;
						
				} catch ( FileNotFoundException e1 ) {

					e1.printStackTrace();
						
				} catch ( IOException e1 ) {
						
					e1.printStackTrace();
				}
				
		   	} else {
		   		
				JOptionPane fileFormatPane = new JOptionPane ( "Info" );
				fileFormatPane.showMessageDialog (
						
						null,
						"Sorry. Currently only these extensions are permitted: \n\n" +
						".conf\n" +
						".html\n" +
						".java\n" +
						".py\n" +
						".rtf\n" +
						".txt\n" +
						".xml\n"
				);
		   	}
	    }
	} // END of openFile()
	
	
	void saveFile () {
		
		JFileChooser fileChooser = new JFileChooser ( "." );
		fileChooser.setFileSelectionMode ( JFileChooser.FILES_ONLY );
		fileChooser.setOpaque ( true );
		
		int ret = fileChooser.showSaveDialog ( null );
			    
		if ( ret == JFileChooser.APPROVE_OPTION ) {
		 
		   	File selectedFile = fileChooser.getSelectedFile();

		   	try {
		   		
		   		file = fileChooser.getSelectedFile(); 
		   		FileWriter writer = new FileWriter( file, true );
		   	    BufferedWriter bw = new BufferedWriter ( writer );
		   		bw.write(editPane.getText());
		   	    bw.newLine();
		   	    
		   	    bw.flush();
		   	    bw.close();
		   	    this.setTitle ( windowTitle + " - " + selectedFile.getAbsolutePath() );
		   	    isFileLoaded = false;
		   	    
			} catch ( FileNotFoundException e1 ) {

				e1.printStackTrace();
					
			} catch ( IOException e1 ) {
					
				e1.printStackTrace();
			}
		}
	} // END of saveFile()
	
	
	void showAbout () {
		
		JOptionPane aboutPane = new JOptionPane ( "about jEditor" );
		aboutPane.showMessageDialog (
				
				null,
				"jEditor 1.0\n" +
				"Created by Amir Rehman 2011\n" +
				"The GPL v3 applies."
		);
	} // END of showAbout(()
	
	void exit () {
		
		int exitQuestion = JOptionPane.showConfirmDialog (
				
				null,
				"Are you sure you want to exit now?\n" +
				"Unsaved changes will be lost!",
				"Done already?",
				JOptionPane.OK_CANCEL_OPTION
		);
		
		if ( exitQuestion == JOptionPane.YES_OPTION )
			System.exit ( 0 );
		else
			return;
	} // END of exit()
	
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> MAIN method
	
	public static void main ( String[] args ) {

		Jeditor editor = new Jeditor();
		
	} // END of main()

} // END of Jeditor
 
1.
Ich schreibe mir einen simplen Texteditor zur Übung. soweit klappt alles, nur beim Speichern hab ich das Problem, dass bereits vorhandene Dateien beim erneuten Speichern nicht überschrieben, sondern nur ergänzt werden, was ja nicht Sinn der Sache ist.
Das liegt am true, dass du dem FileWriter übergibst. Steht auch so in der API.

2.
Ich hab noch nicht herausgefunden, wie man es schafft, dass schon im Öffnen-Dialogfenster nur die Dateiformate angezeigt werden, die auch geöffnet werden dürfen. Momentan umgehe ich das, indem ich eine Fehlermeldung ausgebe, wenn jemand etwas öffnen will, das nicht erlaubt ist.
Dafür gibts den FileFilter (Java 2 Platform SE v1.4.2)
 
2.
Ich hab noch nicht herausgefunden, wie man es schafft, dass schon im Öffnen-Dialogfenster nur die Dateiformate angezeigt werden, die auch geöffnet werden dürfen. Momentan umgehe ich das, indem ich eine Fehlermeldung ausgebe, wenn jemand etwas öffnen will, das nicht erlaubt ist.

JFileChooser (Java Platform SE 6)

Sowas hier? FileFilter musste dir selbst anschauen, aber da kannste soweit ich weiß definieren, welche Dateiendungen akzeptiert werden.

Beispiele dafür gibts auch hier: How to Use File Choosers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)
 
Hey!

Wow! Das ging jetzt aber flott! Ich danke euch beiden sehr! Ich hab das mit dem FileWriter getestet. Das funktioniert nun wirklich. Muss mir den wohl nochmal genauer anschauen. Das mit dem JFileChooser teste ich jetzt. Ich schreibe euch dann gleich, ob es das war oder nicht. Nochmals vielen Dank!


UPDATE:

Alles funktioniert nun wie ich es haben wollte. Vielen Dank nochmal für die Tipps! Das hat mir sehr geholfen.

Wünsche euch noch einen schönen Nachmittag!
 
Zuletzt bearbeitet:

Neue Themen


Zurück
Oben