Switch to full style
Java2 codes,problems ,discussions and solutions are here
Post a reply

How to Load Files using JFileChooser!!

Thu Jun 28, 2007 5:26 am

This topic is about Loading Files using JFileChooser class. The following bit of code will open a Dialog. A window, that in turn will allow a user to search for a file and then by clicking on it and pressing the open button of the JFilechooser, they will load the file into your program.

This will depend on what you are using to view a file... For this, I will be using a JTextArea, and I will be loading Text Files into it.

java code
import java.io.*;
import java.io.File.*;
import java.util.*;
import javax.swing.JFileChooser;

try
{
JFileChooser loadEmp = new JFileChooser();//new dialog
File selectedFile;//needed*
BufferedReader in;//needed*
FileReader reader = null;//needed*,look these three up for further info

//opens dialog if button clicked
if (loadEmp.showOpenDialog(this)==JFileChooser.APPROVE_OPTION)
{
//gets file from dialog
selectedFile = loadEmp.getSelectedFile();
//makes sure files can be processed before proceeding
if (selectedFile.canRead() && selectedFile.exists())
{
reader = new FileReader(selectedFile);
}
}

in = new BufferedReader(reader);

//inputLine recieves file text
String inputLine = in.readLine();
int LineNumber = 0;
while(inputLine!=null)
{
//LineNumber isn't needed, but it adds a line count on the left, nice
LineNumber++;
StringTokenizer tokenizer = new StringTokenizer(inputLine);

//displays text file
jTxtAMain.append(LineNumber+": "+inputLine+"\n");
//next line in File opened
inputLine = in.readLine();
}
//close stream, files stops loading
in.close();
}
//catches input/output exceptions and all subclasses exceptions
catch(IOException ex)
{
jTxtAMain.append("Error Processing File:\n" + ex.getMessage()+"\n");
}
//catches nullpointer exception, file not found
catch(NullPointerException ex)
{
jTxtAMain.append("Open File Cancelled:\n" + ex.getMessage()+"\n");
}

I hope this helps someone.



Post a reply
  Related Posts  to : How to Load Files using JFileChooser!!
 Create Custom Filters For JFileChooser!!!!     -  
 load class to applet- load frame class to applet     -  
 help me How do I load image from my pc to matlab     -  
 Load tweets using JQuery     -  
 J2me Image load Exception     -  
 calculate the load time for a page     -  
 Load RSS feeds and parse it with JQuery     -  
 Load Content to Tabs using AJAX and JQuery     -  
 Add double quotes to text dynamically, on page load     -  
 how to load the form elements depending on selection option     -  

Topic Tags

Java Swing