Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

loading text file into java text area

  • 20-04-2006 12:57PM
    #1
    Closed Accounts Posts: 32


    i think i'm missing something from my code...

    i'm uisng a JFileChooser to open a text file and append it to a text area but it only appends the file location, not what is in the file.
    else if(source == openFile)
    {
    	chooser = new JFileChooser();
    	chooser.setCurrentDirectory(new java.io.File("."));
    	chooser.setDialogTitle(choosertitle);
    			 chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    			if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
    			{
    				//System.out.println("getCurrentDirectory(): " +  chooser.getCurrentDirectory());
    			  	//System.out.println("getSelectedFile() : " +  chooser.getSelectedFile());
    			  	String tmp = ("" +  chooser.getSelectedFile());
    			  	notePad.setText(tmp);
    			}
    			else
    			{
    			  	System.out.println("No Selection ");
    			}
     		}
    

    is it something really simple, i havent done?


Comments

  • Closed Accounts Posts: 619 ✭✭✭Afuera


    You're not actually reading the contents of the file at all here.

    Instead of the code you have which declares the tmp String, you'd need something like this:
    File file = chooser.getSelectedFile();
    if(file != null){
    	String sResult = "", tmp = "";
            // open the file for reading
    	BufferedReader bread = new BufferedReader(new FileReader(file));
            // this reads the file in, one line at a time
    	while((tmp = bread.readLine()) != null){
    		sResult += tmp;
    	}
    	notePad.setText(sResult);
    }
    

    I can't remember off hand but the newline characters might get stripped out using readLine() so you'd need to append them back to the sResult String as you read in each line.

    Hope that makes sense!


  • Closed Accounts Posts: 32 VanStrummer


    excellent mate, works like a charm.

    for the new line thingy, is just added this:

    sResult += tmp + "\n";

    thnx again

    Van


Advertisement