Nathaniel Scerri
Nathaniel Scerri

Reputation: 21

Reading From a text file, creating another file

When I read from a .txt file it is making another copy of the .txt file and adding ".txt" to the name.

For example: read from "hello.txt" and it creates "hello.txt.txt".. I have discovered that the problem is the line containing FileWriter flwrtr = new FileWriter(fl.getPath()+".txt"); but If I remove the string it would not work anyone know a solution ?

  String path="";

  JFileChooser fileopenchooser = new JFileChooser();
  fileopenchooser.setDialogTitle("Open Quiz");
  FileNameExtensionFilter filter = new FileNameExtensionFilter("Text File", "txt");
  fileopenchooser.setFileFilter(filter);

  int getvlue = fileopenchooser.showOpenDialog(fileopenchooser);
  if(getvlue == JFileChooser.APPROVE_OPTION){

      File fl = fileopenchooser.getSelectedFile();
      try{

        FileWriter flwrtr = new FileWriter(fl.getPath()+".txt");
        path = fl.getPath();
        flwrtr.close();

      }
      catch(Exception e){
        JOptionPane.showMessageDialog(null,"Problem Saving File!","ERROR",JOptionPane.WARNING_MESSAGE);
      }

Upvotes: 0

Views: 288

Answers (3)

Edd
Edd

Reputation: 29

again, I've been thinking,...

Better yet if you are aiming a quiz document in a quiz system that is opening files distributed for the quiz participant and then they oopen it then they can fill the form (eg. Pdf form) with answer and signin it(or automatically signed as your login) and submit/save it thus making the system have document of all valid / legal test /quiz document that can be queried dan judge/grade, I think this is how it will goes:

Model:

package com.emerlard.test.temp.test.model;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author eddhie
 */
@Entity
public class Document implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Document)) {
            return false;
        }
        Document other = (Document) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.emerlard.test.temp.test.model.Document[ id=" + id + " ]";
    }

    private String Name;

    private User CreatedBy;


    //todo:create a directory system/model
    private Directory directory;

    `


}-----

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.emerlard.test.temp.test.model;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author eddie
 */
@Entity
public class QuestionDocument extends Document implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof QuestionDocument)) {
            return false;
        }
        QuestionDocument other = (QuestionDocument) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.emerlard.test.temp.test.model.QuestionDocument[ id=" + id + " ]";
    }





} /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.emerlard.test.temp;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author eddhie
 * 
 */
public class JQuizFileChooser extends JFileChooser implements IJQuizFileChooser   {
    //todo:the event still using property change call so maybe need to be regular agent or not. but it is quite standard for this java beans
    public static final String PROP_FILE_CHOOSEN_EVENT = "FileChoosenEvent";

    private String FileChoosenEvent;

    private PropertyChangeSupport propertySupport;


    @Override
    public String getFileChoosenEvent() {
        return FileChoosenEvent;
    }

    @Override
    public void setFileChoosenEvent(String value) {
        String oldValue = FileChoosenEvent;
        FileChoosenEvent = value;
        propertySupport.firePropertyChange(PROP_FILE_CHOOSEN_EVENT, oldValue, FileChoosenEvent);
    }

    //todo:what to do woith mutltipel file seleantion
    @Override
    public void setSelectedFile(File file) {
        super.setSelectedFile(file); //To change body of generated methods, choose Tools | Templates.
        //todo:what aobut mamignt eh proeety hcangei envet is not sring but drectoyr fpeorty
        setFileChoosenEvent("Selected File Changed , do your setting of your hander to fill the containter");

    }



    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertySupport.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertySupport.removePropertyChangeListener(listener);
    }

    public JQuizFileChooser() {
                propertySupport = new PropertyChangeSupport(this);
        this.setFileFilter(new FileNameExtensionFilter("Text File", "txt"));

    }



}

And the interface to tha tcompoent

package com.emerlard.test.temp;

/**
 *
 * @author eddhie
 */
public interface IJQuizFileChooser {

    String getFileChoosenEvent();

    void setFileChoosenEvent(String value);

}

Seee:

Here you can correlate the compojnet of the JquisFileCooser ( incude the interface for injection eg using spring eg.

(although can can jsut use bean for property inection)

Then on you main code

    @autowire
    IQuizFileChooser

This will result the content of this filechooser or handle

Then you can catch the event of the filecchoosen in the main code that will be Like

private void newBean11PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_newBean11PropertyChange
        // TODO add your handling code here:

    }//GEN-LAST:event_newBean11PropertyChange

Where the evt correspondent to your event

And fill the container for the display within

On save then you use some filewriter to write to the proper directory with proper id name

You just connect the record of the model for an easy application model

GOTIT?

SO eventually you just need about all this

@autowire Iquizzfilechooser

@autowire Containner //if you want to do this and You can be running immediately according to what you want to go with it if , other is injection or if you want to add more other things is up to you then

cool right?

Upvotes: 0

eddhie
eddhie

Reputation: 1

Do you notice is that the getPath method is returning path of the file including the file name? I know this can be misleading, that is why you have 2 txt. Maybe you should do some string manipulation for the path like reducing 3 char etc.

e.g: fl.getPath().substring(0, fl.getPath().length()-3)

Upvotes: 0

Michiel Pelt
Michiel Pelt

Reputation: 82

This is Java, not C. You get a new file "hello.txt.txt" because you add the ".txt" in the new FileWriter call. You say you want to read the file, then why create a FileWriter which is for writing to a file, not reading. If you want to read, use FileReader.

Upvotes: 1

Related Questions