11 Replies Latest reply: Feb 15, 2009 1:33 PM by 843785 RSS

    write in a File

    843785
      Hi everybody.

      My problem is that I want to write some information in a File. I can write it using FileOutputStream. But what I want is that each time it writes in a File begin a new line in it. Now all the information save in the same line and it's difficult to understand.

      Is there any way to do it? Here is the class:
      public class otraclase extends JFrame{
           
             JPanel panel1 = new JPanel();
             JButton bAadir = new JButton();
             File f = new File("./Ficherolog.txt");
      
             public otraclase(){
                  
                     super();  //Llamamos al constructor padre
                     try{
                       jbInit();  //Situamos los componentes graficos
                       pack();  //Los visualizamos bien en pantalla
                     }//try
                     catch (Exception ex){
                       ex.printStackTrace();
                     }//catch
                     
                  }//ModificarNodoDialogo
      
             
             public static void main(String args[]){
                  otraclase oc = new otraclase();
                  oc.setVisible(true);
             }
             
             private void jbInit() throws Exception{
                  
                     this.setTitle("Modificar Nodo");
                    this.setBackground(UIManager.getColor("InternalFrame.activeTitleGradient"));
                    this.setEnabled(true);  //Lo habilitamos para que cambie
                    this.setLayout(new BorderLayout());  //Ponemos BorderLayout porque con JSplitPane nos da problemas
                    this.setMinimumSize(new Dimension(400, 400));
                    this.setPreferredSize(new Dimension(400, 400));
      
                     //panel1.setLayout(null);
                     panel1.setLayout(new BorderLayout());
                     panel1.setPreferredSize(new Dimension(400, 400));  //Dimensiones del panel
      
      
                     //Boton bAadir
                     bAadir.setText("Aadir IP");
                     bAadir.setCursor(new Cursor(Cursor.HAND_CURSOR));  //********************MODIFICACION
                     bAadir.addMouseListener(new otraclase_mouseclicked(this));
      
                     //Colocamos los componentes en el panel
                     panel1.setVisible(true);
                     panel1.setPreferredSize(new Dimension(400,400));
                     panel1.setMinimumSize(new Dimension(400,400));
                     add(panel1);
                     
                     
                     panel1.add(bAadir, BorderLayout.PAGE_START);
                           
                     }//jbInit
      
             public void escribir_mouseClicked(){
                  
                    try{
                        FileOutputStream os = new FileOutputStream(f,true);
                        String linea = "I am writing in the file";
                        os.write(linea.getBytes());
                        os.close();
                      }
                      catch(IOException ioe){
                        ioe.printStackTrace();
                        System.out.println("No se pudo guardar el fichero de mensajes de sesion");
                      }
      
                  }//logmsg
           }
      
      class otraclase_mouseclicked extends java.awt.event.MouseAdapter{
             
          otraclase adaptee;
      
          otraclase_mouseclicked(otraclase adaptee) {
               this.adaptee = adaptee;
          }
           
          public void mouseClicked(MouseEvent e) {
             adaptee.escribir_mouseClicked();
          }
             
        }//PantallaRed_bok_mouseAdapter
      Thank you very much.
        • 1. Re: write in a File
          843785
          Hi,

          I think that's not possible, i mean, add lines at begginin of the file is not possible, directly, with JAVA SE. To make this, you must read line by line and write them in a new file in reverse order.

          If you want to add lines at the end of the file you could use the FileWritter method.


          TRANSLATE:
          Hola,

          Creo que no se puede añadir al principio de un archivo directamente con una funcion de la API de JAVA. Para hacer eso lo que tienes que hacer es leer linea por linea y pasarlas a un nuevo fichero en orden inverso.

          Si, por otro lado, lo que quieres es añadir al final tal vez puedas usar la funcion FileWritter que permite añadir al final.

          Un saludo.
          • 2. Re: write in a File
            843785
            Thank you very much.

            Muchas, muchas gracias.
            • 3. Re: write in a File
              843785
              Since you appear to be writing text, if you use a writer of some sort it's easy to write new lines. Have you gone through the Sun IO tutorial yet? If not, I suggest that you do so.
              I think that's not possible, i mean, add lines at begginin of the file is not possible, directly, with JAVA SE. To make this, you must read line by line and write them in a new file in reverse order.
              I'm not sure what you mean by "reverse order" here, but I add lines to the beginnings of files all the time using standard Java, so I don't agree with this statement.
              • 4. Re: write in a File
                843785
                Sorry. But if I use FileWriter I get the same.
                                  FileWriter os = new FileWriter(f,true);
                                  String linea = "I am writing in the file";
                                  os.append(linea);
                What I open the File I get the line:

                I am writing in the fileI am writing in the fileI am writing in the fileI am writing in the file...

                What I want is:
                I am writing in the file
                I am writing in the file

                I dont mind the order of the sentences.
                I have looked at the tutorial but I dont know if I have looked at the right place because I didnt see anything.

                Thank you very much.
                • 5. Re: write in a File
                  843785
                  Not answered
                  • 6. Re: write in a File
                    843785
                    Use a PrintWriter wich uses your FileOutputStream (so: new PrintWriter(os) ).
                    • 7. Re: write in a File
                      843785
                      Thanks but it didnt work. I wrote this:
                      File f = new File("./Fichero.txt");
                      
                      ......
                      
                      FileOutputStream fo = new FileOutputStream(f,true);
                      PrintWriter pw = new PrintWriter(fo);
                      String linea = "I am writing in the file";
                      pw.write(linea);
                      Now the file Fichero.txt is empty. Perhaps the problem is the version. I am using 1.5
                      Thanks.
                      • 8. Re: write in a File
                        843785
                        if the file is empty, it suggests that you're not closing your writer. Do you call close on it? Also, you may wish to post a small compilable program that shows your problem. Also, have you gone through the I/O tutorial yet?

                        good luck
                        • 9. Re: write in a File
                          843785
                          Do you flush your stream before closing it? As seen from your constructor you don't use autoFlush.
                          Further, if you wan't to go to a new line in your file you should use println(String).

                          I thought I gave you the API of PrintWriter, did you actualy read it?
                          • 10. Re: write in a File
                            843785
                            Thanks everybody.

                            Yes I have already read the API PrintWriter, but as the instruction println doesnt write anything I was trying with the instruction write.

                            The problem was close(). I removed this instruction and I didnt realize so the file was empty. Now with println and close it works very well.

                            Thank you everybody and sorry.
                            • 11. Re: write in a File
                              843785
                              No problem, your welcome