简体   繁体   English

如何将TXT文件加载到JList中?

[英]How to load a TXT File into a JList?

I have the following Java code to read a txt file: 我有以下Java代码可以读取txt文件:

    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. 但是我需要将该信息加载到JList ,因此此JList将向我显示我在文件中保存的单词。 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 屏幕截图

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM