How to read a file using jFileChooser after click of a button? - java

I want to read a file using jFileChooser. jFileChooser will come up after press of a button (say jbutton1ChooseFile) and select the required file. After the selection is complete, another button (say jbutton2) will be used to read the contents of the file which has just been selected by the user. So on clicking on jbutton2, selected file will be read.
I am posting few lines of code so that it would be easy to understand what I mean to say:
private void jButton1ChooseFileChooseFileActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser loadFile= new JFileChooser();
loadFile.setApproveButtonText("Select File");
loadFile.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter f1 = new FileNameExtensionFilter("Text Files", "txt", "text","rtf","doc","docx");
loadFile.setFileFilter(f1);
switch (loadFile.showOpenDialog(EncDecApp.this))
{
case JFileChooser.APPROVE_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "Selection Successfull!",
"Attention!",
JOptionPane.OK_OPTION);
jButton1ChooseFile.setText("File Chosen");
jLabelChooseFile.setText(String.valueOf(loadFile.getSelectedFile()).substring(0,30)+"...");
fileSelect=true;
break;
case JFileChooser.CANCEL_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "No file chosen",
"Attention!",
JOptionPane.OK_OPTION);
loadFile.setSelectedFile(null);
jButton1ChooseFile.setText("Browse..");
jLabelChooseFile.setText("Choose file to encrypt");
break;
case JFileChooser.ERROR_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "Error",
"Choosing File",
JOptionPane.OK_OPTION);
loadFile.setSelectedFile(null);
jButton1ChooseFile.setText("Browse..");
jLabelChooseFile.setText("Choose file to encrypt");
}
loadFile.setVisible(true);
}
Upto this it's working perfectly.
Now, the code for jButton2 is as follows:
private void jButton2EncryptEncryptActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//Charset charset=Charset.forName("UTF-8");
int returnVal=loadFile.showOpenDialog(jLabel1);
if(returnVal==loadFile.APPROVE_OPTION)
{
File filePath = loadFile.getSelectedFile();
try{
BufferedReader in = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
jTextArea1.append(line + "\n");
}
in.close();
}
catch(IOException ex)
{
System.err.println("Open plaintext error: "+ex);
}
}
}
Any help will be highly appreciated.

At first glance the problem appears to be that you are using a local variable for the JFileChooser. That is to say, you have the line:
JFileChooser loadFile= new JFileChooser();
In your jButton1ChooseFileChooseFileActionPerformed function, and yet also try to refer to loadFile in your jButton2EncryptEncryptActionPerformed function.
In order to have the loadFile object available to both you need to have said loadFile object be a member of the class to which both functions belong.

Related

Trying to send data to text file

Hi there I made a program that consist of jtextfield and couple jbuttons. I want to press a jbutton so that the jtextfields will be save to the computer. Any help will be useful.
I think this will help you..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jTxt_text.getText().isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "Field is empty. Fill the filed and try again.");
} else {
//get the text from the jTextField and save it into a varibale.
String inputText = jTxt_text.getText();
//Where to save the file.
String savePath = "C:/test/sample.txt";
//Creating a file object, file is an abstract representation of file and directory pathnames.
File tempFile = new File(savePath);
//Check wther the file is available or not.
if (!tempFile.exists()) {
try {
//Creates the file if it's not exsising.
tempFile.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try {
//writing process..
FileWriter tempWriter = new FileWriter(tempFile.getAbsoluteFile());
BufferedWriter tempBufferWriter = new BufferedWriter(tempWriter);
tempBufferWriter.write(inputText);
tempBufferWriter.close();
JOptionPane.showMessageDialog(rootPane, "Text file with the written text is successfully saved.");
jTxt_text.setText(null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Still there's a small problem with this code tempBufferWriter.write(inputText) returns void so.. i don't know how to check wther the process completed successfully from the code itself..

Java Text editor - How to create New File

I followed this tutorial on how to create a simple text editor in Java, but the person who wrote the tutorial seems to have left out how to create a new file http://forum.codecall.net/topic/49721-simple-text-editor/
For the most part I was able to follow the guide, but I have no idea how one would create the 'New File' functionality.
you can write code like this to create new file :
try {
File file = new File("c:\\newfile.txt");
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
When you click on the save button on your text editor, include this in your actionPerformed() method -
FileDialog fd=new FileDialog(f1,"Save Your File",FileDialog.SAVE);
fd.setSize(400,200);
fd.setVisible(true);
try
{
FileWriter fw=new FileWriter(fd.getDirectory()+fd.getFile());
fw.write(t1.getText()); // t1 is the name of your textarea
fw.close();
}
catch(Exception e)
{
}

Show open/save dialog java

I'm trying to save and load .txt files on my program. I've got methods to read and write the files, but I want the user to be able to choose which name and where the files will be saved using the open/save forms. I've done this so far.
JButton btnLoad = new JButton("Carregar");
btnCarregar.addActionListener(new ActionListener() {
private Component modalToComponent;
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
}
}
});
Right, this actually opens the form, but after that, I don't know where and how use my methods to load the text. I guess, I should use file since it's the selected file, but when I send this file to my methods, it just doesnt work. Any example would be appreciated. Thanks before hand!
You can call a method from the point where the user has selected a file to open (in the if part of the actionPerformed method). So if your reading method is called openFile and accepts a File parameter, you can call 'openFile(file)` as the second statement in your if block:
if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
openFile(file);
}
A simple example of an openFile method to handle opening a file (in this case by only printing the contents) could look like this:
private void openFile(final File inputFile) {
try (final BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("line: " + line);
// todo: handle line.
}
} catch (final IOException e) {
e.printStackTrace();
// todo: handle exception.
}
}

How to save file.txt with JFileChooser?

I am developing notepad project, would like know how do for save a file.txt, my problem is, I keep the file opening JFileChooser, after selected the local where save intend, but after if save again will open JFileChoose again. I want save. Not save as.
JFileChooser fc = new JFileChooser();
int resp = fc.showSaveDialog(fc);
if (resp == JFileChooser.APPROVE_OPTION) {
PrintStream fileOut = null;
try {
File file = fc.getSelectedFile();
fileOut = new PrintStream(file);
fileOut.print(txtArea.getText());
} catch (FileNotFoundException ex) {
Logger.getLogger(frmNotePad.class.getName()).log(Level.SEVERE, null, ex);
} finally {
fileOut.close();
}
Change you work flow.
Basically, when you first save the file, you need to keep a reference to the File to which you saved to...
public class ... {
private File currentFile;
Now, when you go to save the file, you need to check if the currentFile is null or not. It it is null, you ask the user to select a file, otherwise, you can go ahead and try and save the file...
if (currentFile == null) {
JFileChooser fc = new JFileChooser();
int resp = fc.showSaveDialog(fc);
if (resp == JFileChooser.APPROVE_OPTION) {
currentFile = fc.getSelectedFile();
}
}
// Used to make sure that the user didn't cancel the JFileChooser
if (currentFile != null) {
PrintStream fileOut = null;
try {
fileOut = new PrintStream(file);
fileOut.print(txtArea.getText());
} catch (IOException ex) {
Logger.getLogger(frmNotePad.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fileOut.close();
} catch (IOException exp) {
}
}
If you want a save as an alternate to a save as, have the program store a File object referencing the currently opened file's path so the program is always aware of what it's editing, then just write to the programs file variable

It's a good practice to call File methods within JFrame class?

It's a good practice to call File methods(like read a text file) within JFrame class or what should I do if not? Thanks for reply.
This is my code:
private void filechooserButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt", "text"));
fileChooser.setAcceptAllFileFilterUsed(false);
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
resultTextArea.setText(null);
filePathTextField.setText(fileChooser.getSelectedFile().getAbsolutePath());
try (BufferedReader buffReader = new BufferedReader(new FileReader(new File(fileChooser.getSelectedFile().getAbsolutePath())))) {
String line;
while ((line = buffReader.readLine()) != null) {
resultTextArea.append(line + "\n");
}
} catch (Exception exc) {
JOptionPane.showMessageDialog(MainGUI.this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
UPDATE : I edited my code to use SwingWorker, so I hope it's better than was:
private class textFileReader extends SwingWorker<Void, Void> {
#Override
protected Void doInBackground() throws Exception {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt", "text"));
fileChooser.setAcceptAllFileFilterUsed(false);
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
resultTextArea.setText(null);
filePathTextField.setText(fileChooser.getSelectedFile().getAbsolutePath());
try (BufferedReader buffReader = new BufferedReader(new FileReader(new File(fileChooser.getSelectedFile().getAbsolutePath())))) {
String line;
while ((line = buffReader.readLine()) != null) {
resultTextArea.append(line + "\n");
}
} catch (Exception exc) {
JOptionPane.showMessageDialog(MainGUI.this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
}
}
return null;
}
}
Taking your question literally, there's nothing wrong with it. Since you can define your own methods, and code structure is somewhat up to the developer, there's nothing technically wrong with doing file handling inside a class that also happens to extend JFrame.
That said, what I think you're actually asking is "Is it a good practice to do file IO from within Swing methods, such as filechooserButtonActionPerformed()?" And the answer to that question is unequivocally no - never do this.
These methods are called by Swing on the UI thread, also known as the Event Dispatch Thread, and while the UI thread is waiting for these methods to return, your application is frozen. It cannot repaint, it cannot respond to user input, nothing. Therefore instead you want to offload IO and other long-running work to other threads. There's a good tutorial in the Swing documentation: Lesson: Concurrency in Swing.
See also: Java Event-Dispatching Thread explanation

Categories