Ouvrir et Enregiter un fichier sur Java

Fermé
Monta^^ Messages postés 11 Date d'inscription lundi 13 octobre 2008 Statut Membre Dernière intervention 9 mai 2009 - 13 oct. 2008 à 16:03
Monta^^ Messages postés 11 Date d'inscription lundi 13 octobre 2008 Statut Membre Dernière intervention 9 mai 2009 - 13 oct. 2008 à 22:01
Bonjour,
je cherche comment ouvrir un fichier et enregistrer un fichier sur Java
mon probleme, c est que je ne sias pas comment inserer un code deja preparé dans mon code;
voici mon code

[code]

import javax.swing.*;
import javax.swing.event.*; //pour les classes swing
import javax.swing.plaf.TextUI;

import java.awt.*; //pour les classes awt
import java.io.*; //pour les classes io
import java.awt.event.*;//pour les classes event
import java.util.*;

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException; // pour la lecture du fichier




public class word extends JFrame {

public word() { /// constructeur
JPanel p = new JPanel(); // panel
setTitle("Parseur WORD NET");//nom du fenetre
p.setLayout(null);
p.setBackground(new Color(255,255,255));
Font f1 = new Font("Comic sans ms",Font.BOLD,20);// style d'écriture
Font f = new Font("Arial",Font.BOLD,12);
Font fo = new Font("Arial",Font.PLAIN,14);
Font fb = new Font("Arial",Font.BOLD,13);
final JTextField text1;
final JTextArea text2;

JLabel jb = new JLabel(new ImageIcon("c:/im.gif"));
jb.setBounds(100,10,370,31);
p.add(jb);


/******************* MENU *************************/





JMenuBar MB = new JMenuBar();
MB.setFont(f);
MB.setBackground(Color.BLACK);
setJMenuBar(MB);

JMenu fichier = new JMenu("Fichier");
fichier.setFont(f);
fichier.setForeground(Color.WHITE);
fichier.setBackground(Color.BLACK);
MB.add(fichier);

JMenu outil = new JMenu("Outil");
outil.setFont(f);
outil.setForeground(Color.WHITE);
outil.setBackground(Color.BLACK);
MB.add(outil);

JMenu aide = new JMenu("Aide");
aide.setFont(f);
aide.setForeground(Color.WHITE);
aide.setBackground(Color.BLACK);
MB.add(aide);

/******************** SOUS MENU **************************/
/****Fichier****/
JMenuItem NOUVEAU = new JMenuItem("Nouveau");
NOUVEAU.setFont(f);
NOUVEAU.setForeground(new Color(50,2,21));
NOUVEAU.setBackground(new Color(255,255,255));
fichier.add(NOUVEAU);

JMenuItem open = new JMenuItem("Ouvrir");
open.setFont(f);
open.setForeground(new Color(50,2,21));
open.setBackground(new Color(255,255,255));
fichier.add(open);

JMenuItem sauvegarder = new JMenuItem("Sauvegarder");
sauvegarder.setFont(f);
sauvegarder.setForeground(new Color(50,2,21));
sauvegarder.setBackground(new Color(255,255,255));
fichier.add(sauvegarder);

JMenuItem quitter = new JMenuItem("Quitter");
quitter.setFont(f);
quitter.setForeground(Color.BLACK);
quitter.setBackground(Color.WHITE);
fichier.addSeparator();
fichier.add(quitter);


/**** Outil ****/

JMenuItem parser = new JMenuItem("Parser");
parser.setFont(f);
parser.setForeground(new Color(50,2,21));
parser.setBackground(new Color(255,255,255));
outil.add(parser);

JMenuItem xml = new JMenuItem("Afficher le fichier XML");
xml.setFont(f);
xml.setForeground(new Color(50,2,21));
xml.setBackground(new Color(255,255,255));
outil.add(xml);
/**** Aide ****/

JMenuItem propos = new JMenuItem("A propos");
propos.setFont(f);
propos.setForeground(Color.BLACK);
propos.setBackground(Color.WHITE);
aide.add(propos);

JMenuItem help = new JMenuItem("Help?");
help.setFont(f);
help.setForeground(Color.BLACK);
help.setBackground(Color.WHITE);
aide.add(help);


/***************** LABEL ****************************/
JLabel l1= new JLabel ("Saisir le mot");
l1.setBounds(20,100,200,20);
l1.setForeground(Color.BLACK);
l1.setFont(f1);
p.add(l1 );

JLabel l2= new JLabel ("Résultat:");
l2.setBounds(50,150,150,20);
l2.setForeground(new Color(0,0,0));
l2.setFont(f1);
p.add(l2 );

/***************** ZONE DE TEXTE ****************************/
text1 = new JTextField(30);
text1.setBorder(BorderFactory.createLineBorder(Color.black));
text1.setBounds(150,100,230,20);
text1.setBackground(Color.WHITE);
text1.setForeground(Color.BLACK);

text1.setFont(fo);
p.add(text1);



// recuperation de la variable

text2 = new JTextArea();
text2.setBorder(BorderFactory.createLineBorder(Color.black));
text2.setBounds(40,180,520,350);
text2.setBackground(Color.WHITE);
text2.setForeground(Color.BLACK);
text2.setFont(fo);
p.add(text2);

/***************** BOUTTON ****************************/
JButton encode = new JButton("Synonyme");
encode.setBorder(BorderFactory.createEtchedBorder());
encode.setBounds(new Rectangle (400,100,80,20));
encode.setForeground(Color.BLACK);
encode.setFont(fb);
p.add(encode);

JButton antonyme = new JButton("Antonyme");
antonyme.setBorder(BorderFactory.createEtchedBorder());
antonyme.setBounds(new Rectangle (485,100,80,20));
antonyme.setForeground(Color.BLACK);
antonyme.setFont(fb);
p.add(antonyme);


/******************* action sur le menu quitter *************************/
quitter.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent eve)
{
System.exit(0);
}
});

/******************* action sur le menu nouveau *************************/
NOUVEAU.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent eve)
{
text1.setText("");
text2.setText("");
}
});

/******************* action sur le Boutton Ouvrir *************************/


/******************* action sur le Boutton sauvegarder *************************/



/** Filter to work with JFileChooser to select java file types. **/


/******************* action sur le Boutton synonme *************************/





/****************ton code de recherche ********************/






/******************* action sur le menu a propos *************************/


/*****************tu ecrire qq mots 3al projet *******************/


/******************* action sur le menu help *************************/


/*****************tu px ecrire ton mail comme help pr contacté*******************/



/******************* Rendre la fenétre visible *************************/
getContentPane().add(p);
setSize(600,600);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(dim.width/2 - this.getWidth()/2, dim.height/2 - this.getHeight()/2);
setResizable(true);
show();

}// fin du constructeur


}// fin du programme

class test
{
public static void main(String args[])
{

word pa = new word();


}
}

[/code]


Merci infinement pour votre aide
A voir également:

3 réponses

Monta^^ Messages postés 11 Date d'inscription lundi 13 octobre 2008 Statut Membre Dernière intervention 9 mai 2009 1
13 oct. 2008 à 18:19
Merci chuka,
ce sont des precieuses conseils
mais voici le code que je veux implementer dans mon projet,
c est un exemple de code deja pret, que je veux integrer dans mon projet
c est le
FileChooserApp.java


[php]

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

/**
* Demonstrate the use of a JFileChooser to open and
* save files. The chooser filers for *.java files. Opening
* the file results in the text fillig a JTextArea component.
* The text can be modified and saved to a new file.
**/
public class FileChooseApp extends JFrame
implements ActionListener
{

JMenuItem fMenuOpen = null;
JMenuItem fMenuSave = null;
JMenuItem fMenuClose = null;

JTextArea fTextArea;

JavaFilter fJavaFilter = new JavaFilter ();
File fFile = new File ("default.java");

/** Create a frame with JTextArea and a menubar
* with a "File" dropdown menu.
**/
FileChooseApp (String title) {
super (title);

Container content_pane = getContentPane ();

// Create a user interface.
content_pane.setLayout ( new BorderLayout () );
fTextArea = new JTextArea ("");

content_pane.add ( fTextArea, "Center");


// Use the helper method makeMenuItem
// for making the menu items and registering
// their listener.
JMenu m = new JMenu ("File");

// Modify task names to something relevant to
// the particular program.
m.add (fMenuOpen = makeMenuItem ("Open"));
m.add (fMenuOpen = makeMenuItem ("Save"));
m.add (fMenuClose = makeMenuItem ("Quit"));

JMenuBar mb = new JMenuBar ();
mb.add (m);

setJMenuBar (mb);
setSize (400,400);
} // ctor

/** Process events from the chooser. **/
public void actionPerformed ( ActionEvent e ) {
boolean status = false;

String command = e.getActionCommand ();
if (command.equals ("Open")) {
// Open a file
status = openFile ();
if (!status)
JOptionPane.showMessageDialog (
null,
"Error opening file!", "File Open Error",
JOptionPane.ERROR_MESSAGE
);

} else if (command.equals ("Save")) {
// Save a file
status = saveFile ();
if (!status)
JOptionPane.showMessageDialog (
null,
"IO error in saving file!!", "File Save Error",
JOptionPane.ERROR_MESSAGE
);

} else if (command.equals ("Quit") ) {
dispose ();
}
} // actionPerformed

/** This "helper method" makes a menu item and then
* registers this object as a listener to it.
**/
private JMenuItem makeMenuItem (String name) {
JMenuItem m = new JMenuItem (name);
m.addActionListener (this);
return m;
} // makeMenuItem

/**
* Use a JFileChooser in Open mode to select files
* to open. Use a filter for FileFilter subclass to select
* for *.java files. If a file is selected then read the
* file and place the string into the textarea.
**/
boolean openFile () {

JFileChooser fc = new JFileChooser ();
fc.setDialogTitle ("Open File");

// Choose only files, not directories
fc.setFileSelectionMode ( JFileChooser.FILES_ONLY);

// Start in current directory
fc.setCurrentDirectory (new File ("."));

// Set filter for Java source files.
fc.setFileFilter (fJavaFilter);

// Now open chooser
int result = fc.showOpenDialog (this);

if (result == JFileChooser.CANCEL_OPTION) {
return true;
} else if (result == JFileChooser.APPROVE_OPTION) {

fFile = fc.getSelectedFile ();
// Invoke the readFile method in this class
String file_string = readFile (fFile);

if (file_string != null)
fTextArea.setText (file_string);
else
return false;
} else {
return false;
}
return true;
} // openFile


/**
* Use a JFileChooser in Save mode to select files
* to open. Use a filter for FileFilter subclass to select
* for "*.java" files. If a file is selected, then write the
* the string from the textarea into it.
**/
boolean saveFile () {
File file = null;
JFileChooser fc = new JFileChooser ();

// Start in current directory
fc.setCurrentDirectory (new File ("."));

// Set filter for Java source files.
fc.setFileFilter (fJavaFilter);

// Set to a default name for save.
fc.setSelectedFile (fFile);

// Open chooser dialog
int result = fc.showSaveDialog (this);

if (result == JFileChooser.CANCEL_OPTION) {
return true;
} else if (result == JFileChooser.APPROVE_OPTION) {
fFile = fc.getSelectedFile ();
if (fFile.exists ()) {
int response = JOptionPane.showConfirmDialog (null,
"Overwrite existing file?","Confirm Overwrite",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.CANCEL_OPTION) return false;
}
return writeFile (fFile, fTextArea.getText ());
} else {
return false;
}
} // saveFile

/** Use a BufferedReader wrapped around a FileReader to read
* the text data from the given file.
**/
public String readFile (File file) {

StringBuffer fileBuffer;
String fileString=null;
String line;

try {
FileReader in = new FileReader (file);
BufferedReader dis = new BufferedReader (in);
fileBuffer = new StringBuffer () ;

while ((line = dis.readLine ()) != null) {
fileBuffer.append (line + "\n");
}

in.close ();
fileString = fileBuffer.toString ();
}
catch (IOException e ) {
return null;
}
return fileString;
} // readFile


/**
* Use a PrintWriter wrapped around a BufferedWriter, which in turn
* is wrapped around a FileWriter, to write the string data to the
* given file.
**/
public static boolean writeFile (File file, String dataString) {
try {
PrintWriter out =
new PrintWriter (new BufferedWriter (new FileWriter (file)));
out.print (dataString);
out.flush ();
out.close ();
}
catch (IOException e) {
return false;
}
return true;
} // writeFile

/** Create the framed application and show it. **/
public static void main (String [] args) {
// Can pass frame title in command line arguments
String title="Frame Test";
if (args.length != 0) title = args[0];
FileChooseApp f = new FileChooseApp (title);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible (true);
} // main

}// class FileChooseApp
import javax.swing.*;
import java.io.*;

/** Filter to work with JFileChooser to select java file types. **/
public class JavaFilter extends javax.swing.filechooser.FileFilter
{
public boolean accept (File f) {
return f.getName ().toLowerCase ().endsWith (".java")
|| f.isDirectory ();
}

public String getDescription () {
return "Java files (*.java)";
}
} // class JavaFilter



/php
3
chuka Messages postés 965 Date d'inscription samedi 11 octobre 2008 Statut Membre Dernière intervention 29 juillet 2010 378
13 oct. 2008 à 16:32
Salut,
quand tu implémentes tes listner sur les boutons, tu devrais pouvoir mettre du code comme:
BufferedWritter ecrire=new BufferedWritter(new FileWriter("PATH\nom_du_fichier",true));
ecrire.write("blablabla");//ou les données que tu dois recup quand tu clique sur le button en question
ecrire.close();
J'espere ca pourra t'aider!!
PS:suis pas un spécialiste de java donc si d'autre personnes ont d'autres idéesi!!
0
Monta^^ Messages postés 11 Date d'inscription lundi 13 octobre 2008 Statut Membre Dernière intervention 9 mai 2009 1
13 oct. 2008 à 22:01
encore pas de reponse :/
-2