Results 1 to 2 of 2

Thread: reading a file

  1. #1

    Thread Starter
    Member
    Join Date
    Apr 2001
    Location
    Hamilton, ON, Canada
    Posts
    43

    reading a file

    What is the easies way to put the contents of a text file into a JTextArea? This is what I got so far.

    try{
    FileReader in = new FileReader(fileChooser.getSelectedFile());
    int c;
    textBox.setText("");

    while ((c = in.read()) != -1) {

    }

    in.close();
    }catch(java.io.IOException f){

  2. #2
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418

    Code:
     import java.io.*; 
     import java.awt.*;
     import javax.swing.*;
     import java.awt.event.*;   
    
      public class FileExample{
        public static void main(String [] args){
           
           JFrame jf = new JFrame("FileReader");
           jf.addWindowListener(new WindowMonitor());
           JTextArea jta = new JTextArea(); 
           jta.setLineWrap(true);
           jta.setWrapStyleWord(true); 
           Container c = jf.getContentPane(); 
           c.add(jta); 
           jf.setSize(400,300); 
           jf.setVisible(true); 
           fill("C:\\Java\\Novice1.txt", jta); 
      } 
    
      public static void fill(String f, JTextArea jta){
      try{
       File file = new File(f); 
       BufferedReader buff = new BufferedReader(new FileReader(file)); 
       char[] c = new char[getFileCharCount(f)]; 
       Character[] C = new Character[c.length];
       int charsread; 
     
      while(true){
       charsread = buff.read(c); 
       if(charsread == -1) break;   
     }
       
         for(int i = 0; i < c.length; ++i){
         C[i] = new Character(c[i]);
         jta.append(C[i].toString());
         }
      }catch(IOException e){System.err.println(e);}
    }
    
      public static int getFileCharCount(String file) {
    
        String lineOnebyOne = null;
        String finalText = null;
        int numberOfChar = 0;
      try{
        BufferedReader br = new BufferedReader(new FileReader(file));
        while ((lineOnebyOne = br.readLine ())!= null){
          finalText += lineOnebyOne;
           numberOfChar = finalText.length();
        }
          br.close();
         }catch(IOException e){System.err.println(e + "getFileCharCount");}
          return numberOfChar;
        }
       }
     class WindowMonitor extends WindowAdapter {
        public void windowClosing(WindowEvent e){
           System.exit(0);
         }
      }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width