开发者

How to load a TXT File into a JList?

开发者 https://www.devze.com 2023-03-04 17:02 出处:网络
I have the following Java code to read a txt file: class ReadFile { public static void main(String [] args) {

I have the following Java code to read a txt file:

    class ReadFile {
        public static void main(String [] args) {
        File archivo = null;
        FileReader fr = null;
        BufferedReader br = null;

      try {
         archivo = new File ("C:\\archivo.txt");
         fr = new FileReader (archivo);
         br = new BufferedReader(fr);

         String line;
         while((line=br.readLine())!=null)
            System.out.println(line);
      }
      catch(Exception e){
         e.printStackTrace();
      }finally{
         try{                    
            if( null != fr ){   
               fr.close();     
       开发者_高级运维     }                  
         }catch (Exception e2){ 
            e2.printStackTrace();
         }
      }
   }

But I need to load that info into a JList, so this JList would show me what words I have saved in the file. Does anyone knows how to do that?


Source

import java.io.*;
import javax.swing.*;
import java.util.Vector;

class ReadFile {

    public static void main(String [] args) {
        File archivo = null;
        FileReader fr = null;
        BufferedReader br = null;

        try {
            archivo = new File ("ReadFile.java");
            fr = new FileReader (archivo);
            br = new BufferedReader(fr);
            // normally I would prefer to use an ArrayList, but JList
            // has a constructor that takes a Vector directly.
            Vector<String> lines = new Vector<String>();

            String line;
            while((line=br.readLine())!=null) {
                System.out.println(line);
                lines.add(line);
            }

            JOptionPane.showMessageDialog(null, new JScrollPane(new JList(lines)));
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if( null != fr ) {
                    fr.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}

Screen shot

How to load a TXT File into a JList?

0

精彩评论

暂无评论...
验证码 换一张
取 消