PDA

View Full Version : Java help needed



tomwakefield
22nd December 2004, 06:47 PM
OK this thread might be around a while because I'll probably need a fair bit of help.

But for now.

public void getText();
{

String source;
try
{

JFileChooser chooser = new JFileChooser();
BufferedReader reader = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{

File selectedFile = chooser.getSelectedFile
reader = new BufferedReader(new FileReader(selectedFile));
source = reader.readLine();
}
}
catch (IOException exception)
{

System.out.println("Error");
}
}

There is my current code to select a file and read the first line of text. Now:
1 - How do I change this so that only *.txt files show in the file chooser window?
2 - How do I change this so that it can read multiple lines (I'm guessing there will have to be a loop somewhere, but I can't work it out)?

Anyone?

I'll positive rep anyone who helps
[threatpromise]and I'll negative rep anyone who posts crap in here[/threat/promise]

White_Hindu
22nd December 2004, 07:22 PM
If you had used the Java API (http://java.sun.com/j2se/1.3/docs/api/), it gives specific instruction on how to use it.

Excerpt:

JFileChooser provides a simple mechanism for the user to choose a file. For information about using JFileChooser, see How to Use File Choosers, a section in The Java Tutorial.

The following code pops up a file chooser for the user's home directory that sees only .jpg and .gif images:


JFileChooser chooser = new JFileChooser();
// Note: source for ExampleFileFilter can be found in FileChooserDemo,
// under the demo/jfc directory in the Java 2 SDK, Standard Edition.
ExampleFileFilter filter = new ExampleFileFilter();
filter.addExtension("jpg");
filter.addExtension("gif");
filter.setDescription("JPG & GIF Images");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
System.out.println("You chose to open this file: "+chooser.getSelectedFile().getName());
}



If you use find(ctrl+f) and search for a class or method name, chances are you'll find it in Sun's Java API.

I believe it will read multiple lines if you make it search for a specific character index or use EOF logic:


while(!file.EOF())
file.read;